使用ajax上传文件,代码如下:
$('#video-upload-btn').on('change', function(){
var file = this.files[0];
var data = new FormData();
data.append('video_file',file);
$.ajax({
type: "POST",
data:data,
url: 'uploadVideo',
dataType:'json',
success: function (res) {
console.log(res);
}
});
});
出现以下错误:
Uncaught TypeError: Illegal invocation
at f (jquery.js:2)
at ci (jquery.js:2)
at Function.p.param (jquery.js:2)
at Function.ajax (jquery.js:2)
at HTMLInputElement.<anonymous> (goodspic.html?id=216:202)
at HTMLInputElement.dispatch (jquery.js:2)
at HTMLInputElement.h (jquery.js:2)
原因:ajax默认的两个参数processData和contentType限制了默认发送给服务器的数据编码类型。
1.contentType:默认值: "application/x-www-form-urlencoded"。发送信息至服务器时内容编码类型,默认值适合大多数情况,但实际上文件上传的时候,Content-Type大致是这样的"multipart/form-data; boundary=----WebKitFormBoundaryyr7L6TwhhOAIoEyn"。
2.processData:默认值: true。默认情况下,通过data选项传递进来的数据,如果是一个对象(技术上讲只要不是字符串),都会处理转化成一个查询字符串,以配合默认内容类型 "application/x-www-form-urlencoded"。如果要发送 DOM 树信息或其它不希望转换的信息,请设置为 false。
解决办法:设置processData与contentType值为false:
$('#video-upload-btn').on('change', function(){
var file = this.files[0];
var data = new FormData();
data.append('video_file',file);
$.ajax({
type: "POST",
data:data,
url: 'uploadVideo',
dataType:'json',
processData: false, // 不处理发送的数据
contentType: false, // 不设置Content-Type请求头
success: function (res) {
console.log(res);
}
});
});