简体   繁体   中英

uploading a file using AJAX

myI have been trying to upload a file to the server and I am having difficulties it seems that the file is not being sent to the server. I found this question How can I upload files asynchronously? But I cant see much being done differently in that example from what I have. I have the following form:

<form id = "selectFileForm" enctype="multipart/form-data" />
<input type = 'file' multiple ='multiple'>
</form>

then in javascript I have the following:

submitForm : function(){
    var uploadFormData = new FormData(document.getElementById("selectFileForm"));

    $.ajax({
        url : "myHandler.ashx/fileUpload",
        type: "POST",
        data : uploadFormData,
        processData : false,
        contentType : false
    });
}

In my handler(ASP 2.0) I have the following code:

private string fileUpload(HttpContext context)
{   
return context.Request.InputStream.Length.ToString();
} 

This handler is giving me a response of 44 which seems small the file is definitely bigger than that. Which makes me believe the the file isn't getting sent in the request.

This answer did help me to resolve my issue... stackoverflow.com/questions/16963787/

Th problem was I needed to add this to my javascript

formData.append('file', $('#file')[0].files[0]);

This will work for a single file upload but if you are using the multiple option on an input type file, you will need a for loop that appends each file like so :

for(var i =0; i < files.length; i++)
{
    uploadFormData.append('file',files[i]);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM