[英]Javascript AJAX Upload File
我已经用JavaScript编写了一个脚本来处理文件的拖放。 当调用“ drop”侦听时,将使用dataTransfer.files(以下函数)捕获文件。
event.preventDefault();
event.stopPropagation();
console.log(event.dataTransfer.files[0]);
uploadFiles = event.dataTransfer.files;
fileBoxUpLoad(uploadFiles);
控制台日志显示文件似乎已正确捕获
File {name: "Changi - 2016.pdf", lastModified: 1473382409845, lastModifiedDate: Fri Sep 09 2016 10:53:29 GMT+1000 (Australian Eastern Standard Time), webkitRelativePath: "", size: 197754, …}
调用fileBoxUpLoad函数,并且当代码到达xmlhttp.send时抛出错误
JSON中意外的令牌o在JSON.parse()的位置1
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);
我理解这意味着我不认为自己并且我看不出我的代码与我已阅读的所有教程有何不同之处时,我正在尝试解析Javascript对象。 有什么建议吗? 谢谢!!
你可以做这样的事情
//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);
}
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.