asp.net and input type=file multiple read data from code behind

10.8k Views Asked by At

I have an

<input type="file" id="files" name="files[]" multiple runat="server" />

I don't use asp:FileUpload because I need to use a jQuery plugin for multiple image previews and for deleting images before upload them.

My question is How can I manage input data from code behind? I have to loop through selected images. I searched on the web and I didn't find anything interesting...

If I try, from code behind to read in this way:

 HttpPostedFile file = Request.Files["files[]"];

I see that Request.Files.Count is always 0.

Thanks in advance!

1

There are 1 best solutions below

8
On BEST ANSWER

To Be Honest a quick search gave me this:

In your aspx :

<form id="form1" runat="server" enctype="multipart/form-data">
 <input type="file" id="myFile" name="myFile" />
 <asp:Button runat="server" ID="btnUpload" OnClick="btnUploadClick" Text="Upload" />
</form>

In code behind :

protected void btnUploadClick(object sender, EventArgs e)
{
    HttpPostedFile file = Request.Files["myFile"];

    //check file was submitted
    if (file != null && file.ContentLength > 0)
    {
        string fname = Path.GetFileName(file.FileName);
        file.SaveAs(Server.MapPath(Path.Combine("~/App_Data/", fname)));
    }
}

Update

Another Quick Search gave me this, if you have multiple files then the solution to get them all would be:

for (int i = 0; i < Request.Files.Count; i++)
{
    HttpPostedFileBase file = Request.Files[i];
    if(file .ContentLength >0){
    //saving code here

 }