?
Solved

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

Posted on 2003-03-22
13
Medium Priority
?
2,281 Views
Last Modified: 2009-03-27
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
0
Comment
Question by:zhiqin
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
13 Comments
 
LVL 28

Expert Comment

by:iboutchkine
ID: 8186307
Try this code

Dim wc As New System.Net.WebClient()

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

Author Comment

by:zhiqin
ID: 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
0
 
LVL 1

Expert Comment

by:tomkyn
ID: 8193170
Did you try the overloaded method?

wc.uploadFile(remoteURI, uploadMethod, localFileName);

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

0
NFR key for Veeam Agent for Linux

Veeam is happy to provide a free NFR license for one year.  It allows for the non‑production use and valid for five workstations and two servers. Veeam Agent for Linux is a simple backup tool for your Linux installations, both on‑premises and in the public cloud.

 

Author Comment

by:zhiqin
ID: 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
0
 
LVL 1

Expert Comment

by:tomkyn
ID: 8193227
In administrative tools, IIS settings, check if home directory has both read and write permissions.
0
 
LVL 1

Expert Comment

by:tomkyn
ID: 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.

0
 

Expert Comment

by:shahkalpesh
ID: 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
0
 
LVL 1

Accepted Solution

by:
tomkyn earned 800 total points
ID: 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.
0
 

Author Comment

by:zhiqin
ID: 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  

0
 
LVL 1

Expert Comment

by:tomkyn
ID: 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");
                  }
            }

      }
0
 
LVL 1

Expert Comment

by:tomkyn
ID: 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");
               }
0
 

Author Comment

by:zhiqin
ID: 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
0
 
LVL 96

Expert Comment

by:Bob Learned
ID: 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
0

Featured Post

New benefit for Premium Members - Upgrade now!

Ready to get started with anonymous questions today? It's easy! Learn more.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

In my previous two articles we discussed Binary Serialization (http://www.experts-exchange.com/A_4362.html) and XML Serialization (http://www.experts-exchange.com/A_4425.html). In this article we will try to know more about SOAP (Simple Object Acces…
Real-time is more about the business, not the technology. In day-to-day life, to make real-time decisions like buying or investing, business needs the latest information(e.g. Gold Rate/Stock Rate). Unlike traditional days, you need not wait for a fe…
In this video we outline the Physical Segments view of NetCrunch network monitor. By following this brief how-to video, you will be able to learn how NetCrunch visualizes your network, how granular is the information collected, as well as where to f…
Add bar graphs to Access queries using Unicode block characters. Graphs appear on every record in the color you want. Give life to numbers. Hopes this gives you ideas on visualizing your data in new ways ~ Create a calculated field in a query: …
Suggested Courses

762 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question