C# MVC Upload File without overwriting previous upload

Viewed 720

I have an

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

Model:

public HttpPostedFileBase UploadedFile { get; set; }

Uploading works fine, but in my "UploadedFile" after postback, there is always just the last upload. I need to upload multiple files without selecting them all at once. I know there is multiple="multiple" that you can add as attribute for the input, but there I would need to select all files at once.

Tried a List, no luck.

So what I need is:

  1. Click Upload button. file prompt opens, select an image, click open, file prompt closes.
  2. Repeat Step 1 choose another Image. No Postback has happened yet.
  3. Send the form/do a post. Both Images should be available in the controller

Currently I just receive the second image.

Anyone can help me with this?

Kind Regards

2 Answers

never tested it but i think this should work for you

<input type="file" id="texboxID" name="uploadedFile[]">
<a href="#" onclick="addFiles()">Add File</a>

    <script>
       function addFiles(){

           $("#myForm").append('<input type="file" name="uploadedFile[]" />')
       }
  </script>

then uploading should be something like this:

function UploadFilesToServer(texboxID) {
    var fileUpload = $("#" + texboxID+"").get(0);
    var files = fileUpload.files;
    var FilesToServer = new FormData();
    for (var i = 0; i < files.length; i++) {
        FilesToServer.append(files[i].name, files[i]);
    }
    $.ajax({
        url: "url",
        type: "POST",
        contentType: false,
        processData: false,
        data: FilesToServer,
        // dataType: "json",
        success: function (result) {
            alert(result);
        },
        error: function (err) {
            alert(err.statusText);
        }
    });
}

hope i understood your question and answered you in a convenient way

you can store the selected files in FileList Array , then use this array to upload the files

html :

<input type="file" id="fileUpload">

jQuery:

$(document).ready(function(){

var fileArray=[];

$("#fileUpload").change(function(e){

var upFile = e.target.files[0];
fileArray.push(upFile);
console.log(fileArray);

});


})

I have tested the array it works fine , but I didn't test it in backend

Related