HTML
<script src="https://code.jquery.com/jquery-3.2.1.min.js">
<input class="file-input" type="file" id="file"/>
<button id="upload-btn">Upload</button>
JS
$(function(){
$("#upload-btn").click(function(){
var formData = new FormData();
formData.append("file", $('#file')[0].files[0]);
formData.append("filename", $('#file')[0].files[0].name);
formData.append("other_key", "value");
$.ajax({
url: "upload_url",
type: 'post',
data: formData,
contentType: false, // do not process the data
processData: false, // do not set contentType
success: function( data, textStatus, xhr ){
console.log( xhr.status );
console.log( data );
},
error: function( xhr, textStatus, errorThrown ){
console.log( xhr.status );
console.log( errorThrown )
}
});
});
});
注意在ajax须将contentType
和processData
设置为false
,让formData
中的file
仅包含二进制数据。否则会抛出Uncaught TypeError :Illegal invocation异常。除了post参数构造不正确外,请求类型错误也会抛出该异常,比如,服务端只接受put而客户端使用post。