3 回答

TA貢獻1777條經驗 獲得超10個贊
您可以使用FormData通過POST請求提交數據。這是一個簡單的示例:
var myFormData = new FormData();
myFormData.append('pictureFile', pictureInput.files[0]);
$.ajax({
url: 'upload.php',
type: 'POST',
processData: false, // important
contentType: false, // important
dataType : 'json',
data: myFormData
});
只要知道請求設置(例如url,方法和參數數據),就不必使用表單來發出ajax請求。

TA貢獻1951條經驗 獲得超3個贊
此處的所有答案仍在使用FormData API。就像"multipart/form-data"沒有表格的上傳一樣。您還可以使用以下命令將文件作為內容直接上傳到POST請求的正文中xmlHttpRequest:
var xmlHttpRequest = new XMLHttpRequest();
var file = ...file handle...
var fileName = ...file name...
var target = ...target...
var mimeType = ...mime type...
xmlHttpRequest.open('POST', target, true);
xmlHttpRequest.setRequestHeader('Content-Type', mimeType);
xmlHttpRequest.setRequestHeader('Content-Disposition', 'attachment; filename="' + fileName + '"');
xmlHttpRequest.send(file);
Content-Type和Content-Disposition標頭用于解釋我們要發送的內容(MIME類型和文件名)。
我也在這里發布了類似的答案。

TA貢獻1847條經驗 獲得超7個贊
基于本教程,這里有一個非?;镜姆椒ǎ?/p>
$('your_trigger_element_selector').on('click', function(){
var data = new FormData();
data.append('input_file_name', $('your_file_input_selector').prop('files')[0]);
// append other variables to data if you want: data.append('field_name_x', field_value_x);
$.ajax({
type: 'POST',
processData: false, // important
contentType: false, // important
data: data,
url: your_ajax_path,
dataType : 'json',
// in PHP you can call and process file in the same way as if it was submitted from a form:
// $_FILES['input_file_name']
success: function(jsonData){
...
}
...
});
});
不要忘記添加適當的錯誤處理
添加回答
舉報