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
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
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
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.
wc.uploadFile(remoteURI, uploadMethod, localFileName);
where uploadMethod is "POST" or "GET" including the quotes.
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
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\\de stinationf ilename", myOriginalFileName);
Trace.Write("myresponse: " + responseArray);
}
While I can upload to a path, I still seem to be having problems uploading to a URL.
private void Button3_Click(object sender, System.EventArgs e)
{
System.Net.WebClient wc = new System.Net.WebClient();
byte[] responseArray = wc.UploadFile ("c:\\inetpub\\wwwroot\\de
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
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
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
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
========================== ========== ========== ========== ===------- ---------- ------8c4c 0677a7f966 0
Content-Disposition: form-data; name="file"; filename="file2.txt"
Content-Type: application/octet-stream
this is test
-----------------------8c4 c0677a7f96 60
========================== ========== ========== ========== ===
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
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
==========================
Content-Disposition: form-data; name="file"; filename="file2.txt"
Content-Type: application/octet-stream
this is test
-----------------------8c4
==========================
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.as px.cs" AutoEventWireup="false" Inherits="casestudy.nny.co m.cu.docum entadd" 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_defaultClientScri pt">
<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("i nitialButt ons").styl e.visibili ty = "hidden";
document.getElementById("c onfirmButt ons").styl e.visibili ty = "visible";
document.getElementById("T extBox1"). disabled=t rue;
document.getElementById("D ropDownLis t1").disab led=true;
document.getElementById("T extBox3"). disabled=t rue;
document.getElementById("H TMLInputFi le1").disa bled=true;
}
function hideConfirmButtons() {
document.getElementById("i nitialButt ons").styl e.visibili ty = "visible";
document.getElementById("c onfirmButt ons").styl e.visibili ty = "hidden";
document.getElementById("T extBox1"). disabled=f alse;
document.getElementById("D ropDownLis t1").disab led=false;
document.getElementById("T extBox3"). disabled=f alse;
document.getElementById("H TMLInputFi le1").disa bled=false ;
}
</script>
</HEAD>
<body style="MARGIN: 0px" onload="window.resizeTo(22 7,328);" MS_POSITIONING="GridLayout ">
<form enctype="multipart/form-da ta" 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 Name</strong ></td>
</tr>
<tr>
<td background="images/dash_bg .gif"><asp :textbox id="TextBox1" runat="server" Width="190px" CssClass="newcsinput"></as p:textbox> </td>
</tr>
<tr>
<td class="bodycopy" style="PADDING-TOP: 14px" align="left"><strong>Docum ent Type</strong></td>
</tr>
<tr>
<td background="images/dash_bg .gif"><asp :dropdownl ist id="DropDownList1" runat="server" Width="190px" CssClass="newcsselect"></a sp:dropdow nlist></td >
</tr>
<tr>
<td class="bodycopy" style="PADDING-TOP: 14px" align="left"><strong>Docum ent
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>Docum ent F ile
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;VISIBILIT Y:visible; POSITION:a bsolute;TO P:265px">< asp:Button id="Button1" runat="server" Text="Confirm" CssClass="submit"></asp:Bu tton>  ; <!- -INPUT type="button" value="Go back" class="submit" onclick="hideConfirmButton s();"><INP UT type="button" value="Upload" class="submit" style="WIDTH: 61px; HEIGHT: 19px" onclick="hideInitialButton s();"-->
<INPUT type="button" value="Cancel" class="submit" onclick="window.close();"> </div>
</td>
</tr>
</table>
<P> </P>
<P> </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. DropDownLi st DropDownList1;
protected System.Web.UI.HtmlControls .HtmlInput File 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"].ToStr ing().Equa ls("true") )
{
Response.Write("<SCRIPT>op ener.doRef reshDocume ntList();w indow.clos e();</SCRI PT>");
}
}
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.B utton1_Cli ck);
this.Load += new System.EventHandler(this.P age_Load);
}
#endregion
private void bindControls()
{
System.Data.SqlClient.SqlC onnection cn1 = new System.Data.SqlClient.SqlC onnection( utilities. getAppSett ing("dbCon nStr"));
System.Data.SqlClient.SqlC ommand cmd1 = new System.Data.SqlClient.SqlC ommand();
cmd1.CommandType = System.Data.CommandType.St oredProced ure;
cmd1.Connection = cn1;
DropDownList1.Items.Clear( );
cmd1.CommandText = "getDocumentTypes";
System.Data.SqlClient.SqlD ataReader myReader;
int itemVal;
string itemStr;
cn1.Open();
myReader = cmd1.ExecuteReader();
while(myReader.Read())
{
itemVal = myReader.GetInt32(0);
itemStr = myReader.GetString(1);
DropDownList1.Items.Add(it emStr);
DropDownList1.Items[DropDo wnList1.It ems.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=fa lse;
if (HtmlInputFile1.PostedFile != null)
{
System.Web.HttpPostedFile myPostedFile = HtmlInputFile1.PostedFile;
fileNameNoPath = System.IO.Path.GetFileName (myPostedF ile.FileNa me);
string fileName = System.IO.Path.GetFileName (myPostedF ile.FileNa me);
string contentType = myPostedFile.ContentType;
int contentLength = myPostedFile.ContentLength ;
myPostedFile.SaveAs("c:\\i netpub\\ww wroot\\ass ets\\" + fileName);
Response.Redirect("./docum entadd.asp x?finished =true");
}
}
}
this is the aspx file:
<%@ Page language="c#" Codebehind="documentadd.as
<!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_defaultClientScri
<meta content="http://schemas.microsoft.com/intellisense/ie5" name="vs_targetSchema">
<LINK href="/casestudystyles.css
<script>
function hideInitialButtons() {
document.getElementById("i
document.getElementById("c
document.getElementById("T
document.getElementById("D
document.getElementById("T
document.getElementById("H
}
function hideConfirmButtons() {
document.getElementById("i
document.getElementById("c
document.getElementById("T
document.getElementById("D
document.getElementById("T
document.getElementById("H
}
</script>
</HEAD>
<body style="MARGIN: 0px" onload="window.resizeTo(22
<form enctype="multipart/form-da
<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 Name</strong
</tr>
<tr>
<td background="images/dash_bg
</tr>
<tr>
<td class="bodycopy" style="PADDING-TOP: 14px" align="left"><strong>Docum
</tr>
<tr>
<td background="images/dash_bg
</tr>
<tr>
<td class="bodycopy" style="PADDING-TOP: 14px" align="left"><strong>Docum
Description</strong></td>
</tr>
<tr>
<td background="images/dash_bg
</tr>
<tr>
<td class="bodycopy" style="PADDING-TOP: 14px" align="left"><strong>Docum
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
</tr>
</table>
<table cellSpacing="0" cellPadding="0" width="196" align="center" border="0">
<tr>
<td vAlign="bottom"><div id="confirmButtons" style="LEFT:10px;VISIBILIT
<INPUT type="button" value="Cancel" class="submit" onclick="window.close();">
</td>
</tr>
</table>
<P> </P>
<P> </P>
</div>
</form>
</body>
</HTML>
And the codebehind...
public class documentadd : System.Web.UI.Page
{
protected System.Web.UI.WebControls.
protected System.Web.UI.WebControls.
protected System.Web.UI.HtmlControls
protected System.Web.UI.WebControls.
protected System.Web.UI.WebControls.
private void Page_Load(object sender, System.EventArgs e)
{
if (!IsPostBack)
{
bindControls();
}
try
{
if (Request["finished"].ToStr
{
Response.Write("<SCRIPT>op
}
}
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.B
this.Load += new System.EventHandler(this.P
}
#endregion
private void bindControls()
{
System.Data.SqlClient.SqlC
System.Data.SqlClient.SqlC
cmd1.CommandType = System.Data.CommandType.St
cmd1.Connection = cn1;
DropDownList1.Items.Clear(
cmd1.CommandText = "getDocumentTypes";
System.Data.SqlClient.SqlD
int itemVal;
string itemStr;
cn1.Open();
myReader = cmd1.ExecuteReader();
while(myReader.Read())
{
itemVal = myReader.GetInt32(0);
itemStr = myReader.GetString(1);
DropDownList1.Items.Add(it
DropDownList1.Items[DropDo
}
DropDownList1.Items.Insert
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=fa
if (HtmlInputFile1.PostedFile
{
System.Web.HttpPostedFile myPostedFile = HtmlInputFile1.PostedFile;
fileNameNoPath = System.IO.Path.GetFileName
string fileName = System.IO.Path.GetFileName
string contentType = myPostedFile.ContentType;
int contentLength = myPostedFile.ContentLength
myPostedFile.SaveAs("c:\\i
Response.Redirect("./docum
}
}
}
actually only this is interesting for you...
if (HtmlInputFile1.PostedFile != null)
{
System.Web.HttpPostedFile myPostedFile = HtmlInputFile1.PostedFile;
fileNameNoPath = System.IO.Path.GetFileName (myPostedF ile.FileNa me);
string fileName = System.IO.Path.GetFileName (myPostedF ile.FileNa me);
string contentType = myPostedFile.ContentType;
int contentLength = myPostedFile.ContentLength ;
myPostedFile.SaveAs("c:\\i netpub\\ww wroot\\ass ets\\" + fileName);
Response.Redirect("./docum entadd.asp x?finished =true");
}
if (HtmlInputFile1.PostedFile
{
System.Web.HttpPostedFile myPostedFile = HtmlInputFile1.PostedFile;
fileNameNoPath = System.IO.Path.GetFileName
string fileName = System.IO.Path.GetFileName
string contentType = myPostedFile.ContentType;
int contentLength = myPostedFile.ContentLength
myPostedFile.SaveAs("c:\\i
Response.Redirect("./docum
}
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
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
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
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
Dim wc As New System.Net.WebClient()
wc.UploadFile("http://www.urll.com/file.txt", "c:\file2.txt")