Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Accessing input type file at server side in asp.net

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?

like image 400
Ajay Avatar asked Jan 04 '10 09:01

Ajay


2 Answers

You'll need to add id and runat="server" attributes like this:

<input type="file" id="MyFileUpload" runat="server" />

Then, on the server-side you'll have access to the control's PostedFile property, which will give you ContentLength, ContentType, FileName, InputStream properties and a SaveAs method etc:

int contentLength = MyFileUpload.PostedFile.ContentLength;
string contentType = MyFileUpload.PostedFile.ContentType;
string fileName = MyFileUpload.PostedFile.FileName;

MyFileUpload.PostedFile.Save(@"c:\test.tmp");

Alternatively, you could use Request.Files which gives you a collection of all uploaded files:

int index = 1;
foreach (HttpPostedFile postedFile in Request.Files)
{
    int contentLength = postedFile.ContentLength;
    string contentType = postedFile.ContentType;
    string fileName = postedFile.FileName;

    postedFile.Save(@"c:\test" + index + ".tmp");

    index++;
}
like image 184
LukeH Avatar answered Nov 18 '22 17:11

LukeH


I think the name tag is required on the file input:

<input type="file" name="file" />

Without this, I don’t get anything back.


Further problems that I had which might be specific to my machine:

I get a

Unable to cast object of type 'System.String' to type 'System.Web.HttpPostedFile'.

error at the line

foreach (HttpPostedFile postedFile in Request.Files)

so my final code looks like this:

for (var i = 0; i < Request.Files.Count; i++)
{
    var postedFile = Request.Files[i]; 

    // do something with file here
}
like image 23
zod Avatar answered Nov 18 '22 17:11

zod