I am using the <input type="file" />
tag to upload a file to the server. How do I access the file at the server side and store it at the server? (The file is an image file)
The client side code is :
<form id="form1" action="PhotoStore.aspx" enctype="multipart/form-data">
<div>
<input type="file" id="file" onchange="preview(this)" />
<input type="submit" />
</div>
</form>
Photostore.aspx.cs has
protected void Page_Load(object sender, EventArgs e)
{
int index = 1;
foreach (HttpPostedFile postedFile in Request.Files)
{
int contentLength = postedFile.ContentLength;
string contentType = postedFile.ContentType;
string fileName = postedFile.FileName;
postedFile.SaveAs(@"c:\test\file" + index + ".tmp");
index++;
}
}
I tried uploading a jpg file. Not able to see a saved file. What is going wrong?
I think the name tag is required on the file input:
Without this, I don’t get anything back.
Further problems that I had which might be specific to my machine:
I get a
error at the line
so my final code looks like this:
If you dont want to use the FileUpload control in the toolbox, Give your input an ID then use form[id] to access the input field and cast it to HtmlInputFile.
example here: http://www.codeproject.com/KB/aspnet/fileupload.aspx
Look into the asp:FileUpload control provided by ASP.NET.
You'll need to add
id
andrunat="server"
attributes like this:Then, on the server-side you'll have access to the control's
PostedFile
property, which will give youContentLength
,ContentType
,FileName
,InputStream
properties and aSaveAs
method etc:Alternatively, you could use
Request.Files
which gives you a collection of all uploaded files:If you give the input-tag an id and add the runat="server" attribute then you can access it easily.
First change your input tag:
<input type="file" id="FileUpload" runat="server" />
Then add the following to your Page_Load method:
This will write your file to a folder of your choice. You can access the PostedFile object if you need to determine the file type or original file name.