Link to home
Start Free TrialLog in
Avatar of zhiqin
zhiqin

asked on

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

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
Avatar of iboutchkine
iboutchkine

Try this code

Dim wc As New System.Net.WebClient()

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

ASKER

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
Did you try the overloaded method?

wc.uploadFile(remoteURI, uploadMethod, localFileName);

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

Avatar of zhiqin

ASKER

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
In administrative tools, IIS settings, check if home directory has both read and write permissions.
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.

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
ASKER CERTIFIED SOLUTION
Avatar of tomkyn
tomkyn

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of zhiqin

ASKER

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  

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");
                  }
            }

      }
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");
               }
Avatar of zhiqin

ASKER

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
Avatar of Bob Learned
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