Greeting.
I want to upload an image together with a description to the server by using ajax.
The fileupload works fine, although I can't figure out how to also extract the text entered.
Basically the form looks like this:
<form id="uploader">
<input id="fileInput" type="file" multiple>
<input type="text" id="fileText" name="fileText" value=" " />
<input type="submit" value="Upload file" />
</form>
The script for the upload to the server looks like this:
document.getElementById('uploader').onsubmit = function () {
var formdata = new FormData(); //FormData object
var fileInput = document.getElementById('fileInput');
//Iterating through each files selected in fileInput
for (i = 0; i < fileInput.files.length; i++) {
//Appending each file to FormData object
formdata.append(fileInput.files[i].name, fileInput.files[i]);
}
//Creating an XMLHttpRequest and sending
var xhr = new XMLHttpRequest();
xhr.open('POST', '/Controller/Action');
xhr.send(formdata);
xhr.onreadystatechange = function () {
if (xhr.readyState == 4 && xhr.status == 200) {
alert(xhr.responseText);
}
}
return false;
}
And on the serverside, in the controller for the related action:
public JsonResult Upload(){
for (int i = 0; i < 9; i++){
HttpPostedFileBase file = Request.Files[i]; //Uploaded files
//Do stuff with uploaded files
}
}
What I've tried:
- Changed the Upload method to take in a string parameter named fileText.
Changed the script to also appent the text to the formdata with these two lines inside the for-loop:
var fileText = document.getElementById('fileText');
formdata.append(fileText.value, fileText.value)
I'm probably missing something in both of my trials but I can't seem to figure out what. Please help!
Regards, Chris