簡體   English   中英

Javascript AJAX上傳文件

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM