简体   繁体   中英

Javascript AJAX Upload File

I have written a script in JavaScript to handle a file drag and drop. When the 'drop' listen is called the file is captured using dataTransfer.files (function below).

    event.preventDefault(); 
    event.stopPropagation();
    console.log(event.dataTransfer.files[0]);
    uploadFiles = event.dataTransfer.files; 
    fileBoxUpLoad(uploadFiles);

Console log shows the file appears to be capture correctly

File {name: "Changi - 2016.pdf", lastModified: 1473382409845, lastModifiedDate: Fri Sep 09 2016 10:53:29 GMT+1000 (Australian Eastern Standard Time), webkitRelativePath: "", size: 197754, …}

The fileBoxUpLoad function is call and when the code gets to the xmlhttp.send it throws an error

Unexpected token o in JSON at position 1 at JSON.parse ()

var formData = new FormData();
    for(var x=0; x<=item.length; x++) 
    {
        formData.append('file', item[x]);
    }

    var xmlhttps = new XMLHttpRequest();
    xmlhttps.open("POST", uri);
    xmlhttps.setRequestHeader('Content-Type', file.type);
    xmlhttps.send(formData);

I understand this means I am trying to parse an Javascript object, when I don't think I am and I can't see where my code is any different to all the tutorials I have read. Any advice? Thanks!!

You can do something like this

//declare an array for store the files
var uploadedFiles = [];

//then get files by using their id or maybe you can loop through on your control
var file = $('input[name=YourControlName]').get(0).files[0];

//push the files to array
uploadedFiles.push(file);

//declare form data and append files to form data
var formData = new FormData();   
for (var i = 0; i < uploadedFiles.length; i++) {
    formData.append("file" + i, uploadedFiles[i]);
}

//then you can post to via ajax and get on api via request files
$.ajax({
type: "post",
url: "",
contentType: false,
data: formData,
processData: false,
success: function (result) {
    alert(result);
},
failure: function (e) {
    alert(e);
}

});

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