How to access single element of httppostedfilebase array?

348 Views Asked by At

I am working on ASP.NET MVC web app.I want to upload multiple files on single input control. In my view:

<input type="file" name="files" multiple="multiple">

My model:

public HttpPostedFileBase[] files { get; set; }

Now, in my controller, I am trying to access each file as:

if (files[0] == null)
{
}
if (files[1] == null)
{
}

But if object is not present at that index, it's giving exception:

"Index was outside the bounds of the array."

So how to check if object is present at that index? I cannot use foreach because I want to treat each file separately. So is there any other option than foreach to do this?

1

There are 1 best solutions below

0
On

If you are going to treat the files differently, then I assume you know how to Identity each of the files separately. If this is so, why not name the files, something like this.

//javascript
if (this) {

//code to identify what file is what

fileData.append("ticket", this.files[0]);//assuming you have identified it as so
fileData.append("passport", this.files[1]);//assuming you have identified it as so

$.ajax({
    url: '/ctrl/Upload',
    type: "POST",
    async: true,
    contentType: false, // Not to set any content header  
    processData: false, // Not to process data  
    data: fileData,

    success: function (result) {
        //success
    },
    error: function (err) {
        console.log(err);
    },
    complete: function () {
        //complete
    }
});
}

Then from your controller you can do this

//c#
public ActionResult Upload()
{
    var files = System.Web.HttpContext.Current.Request.Files;
    var result = UploadFile(currentUser, files);
}
UploadFile(HttpPostedFileBase[] files)
{
    string formKey1 = "ticket";
    string formKey2 = "passport";

    var file1 = System.Web.HttpContext.Current.Request.Files[formKey1];
    var file2 = System.Web.HttpContext.Current.Request.Files[formKey2];

    {
        //treat file 1
    }

    {
        //treat file 2
    }
}