Question

how to implicitly upload file from client pc using ASP.net

Asked by: zhiqin

hi,

Can anyone teach me how to use asp.net in order to upload a file in the webserver which is located in the client computer.

When the client click on the Upload button , file located in the client pc of "c:\temp\test.wav" will be uploaded to the webserver(note:the client will no need to locate the file by himself)

Thanks

From Steve

This Question has been solved and asker verified All Experts Exchange premium technology solutions are available to subscription members.

Subscribe now for full access to Experts Exchange and get

Instant Access to this Solution

  • Plus...
  • 30 Day FREE access, no risk, no obligation
  • Collaborate with the world's top tech experts
  • Unlimited access to our exclusive solution database
  • Never be left without tech help again

Subscribe Now

Asked On
2003-03-22 at 01:57:58ID20559480
Tags

file

,

upload

,

client

Topic

.NET

Participating Experts
4
Points
200
Comments
13

Trusted by hundreds of thousands everyday for fast, accurate and reliable tech support.

  • "The time we save is the biggest benefit of Experts Exchange to Warner Bros. What could take multiple guys 2 hours or more each to find is accessed in around 15 minutes on Experts Exchange." Mike Kapnisakis, Warner Bros.
  • "Our team likes having a resource that is more secure than just using Google and most experts using this service really know their stuff. It's nice to look here first versus using Google." Dayna Sellner, Lockheed Martin
  • "Anytime that I've been stumped with a problem, 9 out of 10 times Experts Exchange has either the accepted solution or an open discussion of the potential solution to the problem." Kenny Red, eBay Inc.

See what Experts Exchange can do for you.

Got a question?

We've got the answer.

Experts Exchange has been collecting answers to technology questions since 1996…3 million and counting! If you have a question, chances are we already have your answer.

Screenshot of Experts Exchange Knowledgebase

Need individual assistance?

Our experts are ready to help.

If you can't find the exact answer you're looking for, ask our exclusive community of 50,000 experts. You’ll get a personalized answer from a trusted professional.

Screenshot of Experts Exchange Knowledgebase

Want to learn from the best?

Read articles from industry experts.

Thousands of free tech tips, tricks, how-to’s and tutorials are available in our peer reviewed articles section. See for yourself how smart our experts are, no login required.

Screenshot of an Article

Working on a long term project?

Store your work and research.

Save solutions to your questions, answers you’ve discovered through searching plus helpful articles in your personal knowledgebase for easy future access.

Screenshot of Experts Exchange Knowledgebase

Access the answers to your technology questions today.

Subscribe Now

30-day free trial. Register in 60 seconds.

What Makes Experts Exchange Unique?

Members of the expert community talk about why the experience at Experts Exchange is different than what you will find anywhere else.

Trusted by the world's most respected brands.

image of each brand's logo

Faithfully serving IT professionals since 1996.

Experts Exchange Logo

Try it out and discover for yourself.

Subscribe Now

30-day free trial. Register in 60 seconds.

Related Solutions

  1. ASP.Net
    Where can i get sample code forum like this in EE using ASP.Net?
  2. webserver
    I am installing a deployment process of transfering all my .NET files into a server machine. The deployment process is taken care of, although on a fresh new machine thats running windows XP, I need a step process of how to make the machine run as a webserver, like first ins...
  3. Error:ASP.NET 1.1 is not installed or not registered on …
    I am getting the following error when I am running program in VisualStudio.net.But on my machine IIS was installed Error: Asp.Net 1.1 is not insalled or not registered on your webserver
  4. Videos teaching programming in .NET
    Dear all, I am having difficulties in having to learn a programming language just by reading the book. Do you know any good website that teach ASP.NET using videos?

Free Tech Articles

  1. WARNING: 5 Reasons why you should NEVER fix a computer for free.
    It is in our nature to love the puzzle. We are obsessed. The lot of us. We love puzzles. We love the challenge. We thrive on finding the answer. We hate disarray. It bothers us deep in our soul. W...
  2. SCCM OSD Basic troubleshooting
    SCCM 2007 OSD is a fantastic way to deploy operating systems, however, like most things SCCM issues can sometimes be difficult to resolve due to the sheer volume of logs to sift through and the dispe...
  3. Migrate Small Business Server 2003 to Exchange 2010 and Windows 2008 R2
    This guide is intended to provide step by step instructions on how to migrate from Small Business Server 2003 to Windows 2008 R2 with Exchange 2010. For this migration to work you will need the fo...
  4. Create a Win7 Gadget
    This article shows you how to create a simple "Gadget" -- a sort of mini-application supported by Windows 7 and Vista. Gadgets can be dropped anywhere on the desktop to provide instant information, ...
  5. Outlook continually prompting for username and password
    There have been a lot of questions recently regarding Outlook prompting for a username and password whilst using Exchange 2007. There are a few reasons why this would happen and I will try to cover t...
  6. Backup Exchange 2010 Information Store using Windows Backup
    There seems to be quite a lot of confusion around the ability to backup Exchange 2010 using the built in Windows Backup feature. This stems from the omission of this feature prior to Exchange 2007 s...

Cloud Class Webinars

  1. Avoiding Bugs in Microsoft Access
    Alison Balter takes and in-depth look at avoiding bugs in Access. In this webinar you will learn about using the immediate window to debug your applications, invoking the debugger, using breakpoints to troubleshoot, stepping through code, setting the next statement to execute, ...
  2. Top 10 Best New Features in Visio 2010
    Scott Helmers gives live demonstrations of the top 10 new features in Visio 2010. This webinar will teach you how to create compelling diagrams by adding shapes to the page with a single click, linking the shapes in a diagram to data in Excel (or SQL Server, or SharePoint), ...
  3. IT Consultant Business Secrets Revealed
    Michael Munger, Experts Exchange tech pro and IT consultant, pulls back the curtain on his very successful businesses and answers question on every IT consultant and business owner should know about. He shares secrets on what he did to solve the 5 most common problems in IT, ...
  4. Disaster Recovery and Business Continuity
    Quest CTO, Mike Billon, gives an overview of the steps involved in building a dunamic disaster recovery plan. Through case studies and an examination of software/hardware tooles for monitoring and testing, you'll gain a better understandin of where you are, where you want ...
  5. Organize Your Visio Diagrams with Containers and Lists
    Scott Helmers uses cross functional flowcharts, wireframe diagrams, data graphic legends and seating charts to teach you: how to ustilize all three new structured diagram components in Visio 2010, the best practices for organizeing shapes in previous version of Visio, how to organize ...
  6. How to Us Objects, Properties, Events and Methods in Microsoft Access
    Alison Dalter gives an in-depbth look at objects, properties, events and methods in Microsoft Access. In this webinar you will learn about using the object browser, referring to objects, working with properties and methods, working with object variables, understanding the ...

Join the Community

Give a Little. Get a Lot.

Join the community of experts here and help other tech pros by answering question in your area of expertise. You can earn FREE access to all Experts Exchange's premium features and resources.

Join the Community

Answers

 

by: iboutchkinePosted on 2003-03-22 at 06:13:17ID: 8186307

Try this code

Dim wc As New System.Net.WebClient()

wc.UploadFile("http://www.urll.com/file.txt", "c:\file2.txt")

 

by: zhiqinPosted on 2003-03-22 at 09:35:28ID: 8186878

Dears,

thanks for ur reply. i tried out ur solution but it returns me a wrong message of "The remote server returned an error: (405) Method Not Allowed. "

i put the upload file to the webserver as "http://127.0.0.1/test/file.txt"

Coding...
==========================================================
Sub Button1_Click(sender As Object, e As EventArgs)
    Dim wc As New System.Net.WebClient()
    try
    wc.UploadFile("http://127.0.0.1/test/file.txt", "c:\file2.txt")
   
     catch err as Exception
        label1.text=err.ToString()
    end try
    End Sub
============================================================


i've allowed the maximum read, write permission for the "test" folder in either IIS or explorer folder properties.
Besides, i also make the ASPNET and IUSR_MY to be the user group of
"administrator" level
 
What's wrong there? Can u kindly enlighten me ?

Thanks

NO WAR

Best Regards
Steve

 

by: tomkynPosted on 2003-03-23 at 22:06:49ID: 8193170

Did you try the overloaded method?

wc.uploadFile(remoteURI, uploadMethod, localFileName);

where uploadMethod is "POST" or "GET" including the quotes.

 

by: zhiqinPosted on 2003-03-23 at 22:21:45ID: 8193217

Dears,

i tried
 
wc.UploadFile("http://127.0.0.1/test/file.txt","POST", "c:\test2\file2.txt")

AND

wc.UploadFile("http://127.0.0.1/test/file.txt","GET", "c:\test2\file2.txt")
 
but none of them work. it still returns  "The remote server returned an error: (405) Method Not Allowed. "

I'm using win2k professional running IIS server.
is it any security setting that i missed ?
kindly inform me.

thanks

From Steve

 

by: tomkynPosted on 2003-03-23 at 22:25:39ID: 8193227

In administrative tools, IIS settings, check if home directory has both read and write permissions.

 

by: tomkynPosted on 2003-03-23 at 22:36:54ID: 8193272

Just tried this and it works...

private void Button3_Click(object sender, System.EventArgs e)
{
System.Net.WebClient wc = new System.Net.WebClient();
byte[] responseArray = wc.UploadFile ("c:\\inetpub\\wwwroot\\destinationfilename", myOriginalFileName);
Trace.Write("myresponse: " + responseArray);
}

While I can upload to a path, I still seem to be having problems uploading to a URL.

 

by: shahkalpeshPosted on 2003-03-24 at 01:27:34ID: 8193854

Hello,

To upload a file, there must be a receiving page on the server, which gets the data in binary format & stores it on the webserver

so when you are uploading the URL should be of the page which will receive the data & not the way it is mentioned above

check out any of the website, which takes uploaded things
they have
<form part=multipart/form-data action="someasp.asp">
</form>

I hope you get a clue from this. So in your case
wc.UploadFile("http://127.0.0.1/test/file.asp", "c:\file2.txt")
where file.asp is a page which will receive the data & using some component, it can save the file on the webserver

HTH
Kalpesh

 

by: tomkynPosted on 2003-03-24 at 04:53:24ID: 8194666

You do not need the above in ASP.NET -- all you need is a correctly configured security permissions on the server and you handle your upload during a postback event.

 

by: zhiqinPosted on 2003-03-24 at 06:11:52ID: 8195168

Dear tomkyn,

Thanks for ur advice , it works.
but that is another serius problem there, have u discovered it ?
let me show u the problem

this is the content of the  original file "client.txt" in client PC

===========================================================
this is test
===========================================================

this is the content of the file "server.txt" that has been uploaded to the webserver

===========================================================-----------------------8c4c0677a7f9660
Content-Disposition: form-data; name="file"; filename="file2.txt"
Content-Type: application/octet-stream

this is test
-----------------------8c4c0677a7f9660
===========================================================

can u see the difference in the content of the 2 files ? Actually the file that i would like to upload is in .wav file format. So when this extra stuff is added to the uploaded wav file , there will cause the invalid file format error when i tried to play the wav file
in webserver.

Do u have any idea to remove this extra stuff ?

thanks

HAve a nice day .

Best Regards
Steve  

 

by: tomkynPosted on 2003-03-24 at 18:38:01ID: 8199921

There is my final solution I use...

this is the aspx file:
<%@ Page language="c#" Codebehind="documentadd.aspx.cs" AutoEventWireup="false" Inherits="casestudy.nny.com.cu.documentadd" Trace="true"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" >
<HTML>
      <HEAD>
            <title>documentadd</title>
            <meta content="Microsoft Visual Studio 7.0" name="GENERATOR">
            <meta content="C#" name="CODE_LANGUAGE">
            <meta content="JavaScript" name="vs_defaultClientScript">
            <meta content="http://schemas.microsoft.com/intellisense/ie5" name="vs_targetSchema">
            <LINK href="/casestudystyles.css" type="text/css" rel="stylesheet">
            <script>
function hideInitialButtons() {
      document.getElementById("initialButtons").style.visibility = "hidden";
      document.getElementById("confirmButtons").style.visibility = "visible";
      document.getElementById("TextBox1").disabled=true;
      document.getElementById("DropDownList1").disabled=true;
      document.getElementById("TextBox3").disabled=true;
      document.getElementById("HTMLInputFile1").disabled=true;
}

function hideConfirmButtons() {
      document.getElementById("initialButtons").style.visibility = "visible";
      document.getElementById("confirmButtons").style.visibility = "hidden";
      document.getElementById("TextBox1").disabled=false;
      document.getElementById("DropDownList1").disabled=false;
      document.getElementById("TextBox3").disabled=false;
      document.getElementById("HTMLInputFile1").disabled=false;
}
            </script>
      </HEAD>
      <body style="MARGIN: 0px" onload="window.resizeTo(227,328);" MS_POSITIONING="GridLayout">
            <form enctype="multipart/form-data" method="post" name="documentadd" id="documentadd" runat="server">
                  <div style="WIDTH: 100%; HEIGHT: 100%; BACKGROUND-COLOR: #acabab">
                        <table style="WIDTH: 100%; HEIGHT: 100%; BACKGROUND-COLOR: #cc0001" cellSpacing="0" cellPadding="0" border="0">
                              <tr>
                                    <td class="editlisthead" style="PADDING-BOTTOM: 6px; PADDING-TOP: 6px">Upload a
                                          document</td>
                              </tr>
                        </table>
                        <table cellSpacing="0" cellPadding="0" width="196" align="center" border="0">
                              <tr>
                                    <td class="bodycopy" style="PADDING-TOP: 14px" align="left"><strong>Short
                                                Document&nbsp;Name</strong></td>
                              </tr>
                              <tr>
                                    <td background="images/dash_bg.gif"><asp:textbox id="TextBox1" runat="server" Width="190px" CssClass="newcsinput"></asp:textbox></td>
                              </tr>
                              <tr>
                                    <td class="bodycopy" style="PADDING-TOP: 14px" align="left"><strong>Document Type</strong></td>
                              </tr>
                              <tr>
                                    <td background="images/dash_bg.gif"><asp:dropdownlist id="DropDownList1" runat="server" Width="190px" CssClass="newcsselect"></asp:dropdownlist></td>
                              </tr>
                              <tr>
                                    <td class="bodycopy" style="PADDING-TOP: 14px" align="left"><strong>Document
                                                Description</strong></td>
                              </tr>
                              <tr>
                                    <td background="images/dash_bg.gif"><asp:textbox id="TextBox3" runat="server" Width="190px" CssClass="newcsinput" Height="60px" TextMode="MultiLine"></asp:textbox></td>
                              </tr>
                              <tr>
                                    <td class="bodycopy" style="PADDING-TOP: 14px" align="left"><strong>Document&nbsp;File
                                                Name</strong></td>
                              </tr>
                              <tr>
                                    <td>
                                          <INPUT class="newcsselect" id="HtmlInputFile1" style="BORDER-RIGHT: 1px solid; BORDER-TOP: 1px solid; BORDER-LEFT: 1px solid; WIDTH: 190px; PADDING-TOP: 2px; BORDER-BOTTOM: 1px solid" type="file" name="HtmlInputFile1" runat="server">
                                    </td>
                              </tr>
                              <tr>
                                    <td background="images/dash_bg.gif"></td>
                              </tr>
                        </table>
                        <table cellSpacing="0" cellPadding="0" width="196" align="center" border="0">
                              <tr>
                                    <td vAlign="bottom"><div id="confirmButtons" style="LEFT:10px;VISIBILITY:visible;POSITION:absolute;TOP:265px"><asp:Button id="Button1" runat="server" Text="Confirm" CssClass="submit"></asp:Button>&nbsp;&nbsp;<!--INPUT type="button" value="Go back" class="submit" onclick="hideConfirmButtons();"><INPUT type="button" value="Upload" class="submit" style="WIDTH: 61px; HEIGHT: 19px" onclick="hideInitialButtons();"-->
                                                &nbsp;&nbsp;<INPUT type="button" value="Cancel" class="submit" onclick="window.close();"></div>
                                    </td>
                              </tr>
                        </table>
                        <P>&nbsp;</P>
                        <P>&nbsp;</P>
                  </div>
            </form>
      </body>
</HTML>

And the codebehind...

      public class documentadd : System.Web.UI.Page
      {
            protected System.Web.UI.WebControls.TextBox TextBox1;
            protected System.Web.UI.WebControls.DropDownList DropDownList1;
            protected System.Web.UI.HtmlControls.HtmlInputFile HtmlInputFile1;
            protected System.Web.UI.WebControls.TextBox TextBox3;
            protected System.Web.UI.WebControls.Button Button1;

            private void Page_Load(object sender, System.EventArgs e)
            {
                  if (!IsPostBack)
                  {
                        bindControls();
                  }

                  try
                  {
                        if (Request["finished"].ToString().Equals("true"))
                        {
                              Response.Write("<SCRIPT>opener.doRefreshDocumentList();window.close();</SCRIPT>");
                        }
                  }
                  catch (Exception) {}
            }

            #region Web Form Designer generated code
            override protected void OnInit(EventArgs e)
            {
                  //
                  // CODEGEN: This call is required by the ASP.NET Web Form Designer.
                  //
                  InitializeComponent();
                  base.OnInit(e);
            }
            
            /// <summary>
            /// Required method for Designer support - do not modify
            /// the contents of this method with the code editor.
            /// </summary>
            private void InitializeComponent()
            {    
                  this.Button1.Click += new System.EventHandler(this.Button1_Click);
                  this.Load += new System.EventHandler(this.Page_Load);

            }
            #endregion


            private void bindControls()
            {
                  System.Data.SqlClient.SqlConnection cn1 = new System.Data.SqlClient.SqlConnection(utilities.getAppSetting("dbConnStr"));
                  System.Data.SqlClient.SqlCommand cmd1 =  new System.Data.SqlClient.SqlCommand();
                  cmd1.CommandType = System.Data.CommandType.StoredProcedure;
                  cmd1.Connection = cn1;

                  DropDownList1.Items.Clear();
                  cmd1.CommandText = "getDocumentTypes";
                  System.Data.SqlClient.SqlDataReader myReader;
                  int itemVal;
                  string itemStr;

                  cn1.Open();
                  myReader = cmd1.ExecuteReader();
                  while(myReader.Read())
                  {
                        itemVal = myReader.GetInt32(0);
                        itemStr = myReader.GetString(1);
                        DropDownList1.Items.Add(itemStr);
                        DropDownList1.Items[DropDownList1.Items.Count-1].Value = itemVal.ToString();
                  }
                  DropDownList1.Items.Insert(0, "Select Document Type");
                  myReader.Close();
                  cn1.Close();
            }

            private void Button1_Click(object sender, System.EventArgs e)
            {
                  System.Net.WebClient wc = new System.Net.WebClient();
                  string shortName = TextBox1.Text;
                  string fileNameNoPath="";
                                    
                  TextBox1.Enabled=true;
                  TextBox3.Enabled=true;
                  DropDownList1.Enabled=true;
                  HtmlInputFile1.Disabled=false;

                  if (HtmlInputFile1.PostedFile != null)
                  {
                        System.Web.HttpPostedFile myPostedFile = HtmlInputFile1.PostedFile;
                        fileNameNoPath = System.IO.Path.GetFileName(myPostedFile.FileName);
                        string fileName = System.IO.Path.GetFileName(myPostedFile.FileName);
                        string contentType = myPostedFile.ContentType;
                        int contentLength = myPostedFile.ContentLength;
                        myPostedFile.SaveAs("c:\\inetpub\\wwwroot\\assets\\" + fileName);
                  

                        Response.Redirect("./documentadd.aspx?finished=true");
                  }
            }

      }

 

by: tomkynPosted on 2003-03-24 at 18:39:10ID: 8199927

actually only this is interesting for you...

if (HtmlInputFile1.PostedFile != null)
               {
                    System.Web.HttpPostedFile myPostedFile = HtmlInputFile1.PostedFile;
                    fileNameNoPath = System.IO.Path.GetFileName(myPostedFile.FileName);
                    string fileName = System.IO.Path.GetFileName(myPostedFile.FileName);
                    string contentType = myPostedFile.ContentType;
                    int contentLength = myPostedFile.ContentLength;
                    myPostedFile.SaveAs("c:\\inetpub\\wwwroot\\assets\\" + fileName);
               

                    Response.Redirect("./documentadd.aspx?finished=true");
               }

 

by: zhiqinPosted on 2003-03-24 at 19:32:31ID: 8200083

Dears,

yes u're right, this is the part i'm interested.
But...i'm interested to remove them instead of adding them.

Besides, As i mentioned. i'll like to implicitly upload the file which means that the client site will not need to browse for the file by themself.

Once the client click submit button, the file located in client pc of c:\test\
by default will be automatically uploaded to the server.

i wonder why the file information will be added to the content of the original file when it is uploaded in the server site while the webclient.uploadfile method is using.

And also how to remove this extra stuff so that it will same as original file in client PC.

Thanks

Best Regards

Steve

 

by: TheLearnedOnePosted on 2003-11-05 at 08:58:37ID: 9688188

No comment has been added lately, so it's time to clean up this TA.
I will leave a recommendation in the Cleanup topic area that this question is:

Answered by tomkyn

Please leave any comments here within the next seven days.

PLEASE DO NOT ACCEPT THIS COMMENT AS AN ANSWER!

TheLearnedOne
EE Cleanup Volunteer

20120131-EE-VQP-002

3 Ways to Join

30-Day Free Trial

The Experts

98% positive feedback on 31,087 answers since March 2000. angeliii is a Microsoft Most Valuable Professional for his work with MS SQL Server & Develoment.

He has also proven his knowledge of Visual Basic Programming, PHP Scripting and Oracle Databases.

The Experts

97% positive feedback on 10,752 answers since July 2000. lrmoore has more than 18 years experience in the networking industry.

The six-time Mircosoft MVPs specialties include firewalls, virtual private networking, and network management.

Testimonials

"...and excellent source for support... Kind of like having your very own IT dept." Electriciansnet

Testimonials

"I was apprehensive at signing up at first. However... it has already made my life as an IT administrator much easier." JaCrews

Testimonials

"WOW! You guys have great, active, and knowledgeable people on here." moore50

Business Clients

Business Clients

In the Press

"If you’ve got a question... Experts Exchange can supply an answer.”

In the Press

"...an invaluable aid for both IT professionals and those who require tech support."

In the Press

"where IT professionals provide quick answers on just about any topic"

Business Account Plans

Loading Advertisement...