When uploading pictures, you need to provide the user's login token and the pictures to be uploaded. But how can two different data types be posted to the server together?
mui.init();
function fsubmit(){
var data = new FormData(mui('#uploadForm')[0]); //獲取圖片
$.ajax({
url: 'http://192.168.1.8/api/user-center/avatar',
type: 'POST',
data: {
key:localStorage.getItem('key'), //獲取本地的登錄令牌
avatar:data //圖片
},
cache: false,
processData: false,
contentType: false ,
success:function(data){
console.log(data.datas.testURL);
},
error:function(xhr,type,error){
console.log(xhr.status+xhr.responseText);
//一直返回401,沒有權(quán)限
}
});
return false;
}
Change the data type of post to formdata, and then load the object in formdata. The following is an example:
var fd = new FormData();
var file_data = $('input[type="file"]')[0].files; // for multiple files
for(var i = 0;i<file_data.length;i++){
fd.append("file_"+i, file_data[i]);
}
var other_data = $('form').serializeArray();
$.each(other_data,function(key,input){
fd.append(input.name,input.value);
});
$.ajax({
url: 'caiyongji.com/segmentfault',
data: fd,
contentType: false,
processData: false,
type: 'POST',
success: function(data){
console.log(data);
}
});
You have already created the new FormData, so don’t save objects by yourself. Just use the new one...
mui.init();
function fsubmit() {
var fData = new FormData(); //這里用空的就行,后邊再append
fData.append('file', mui('#uploadForm')[0], '不知道你文件名是啥你自己去整下.jpg');
fData.append('key', localStorage.getItem('key')); //獲取本地的登錄令牌
$.ajax({
url: 'http://192.168.1.8/api/user-center/avatar',
type: 'POST',
data: fData,
processData: false,
contentType: false,
success: function (data) {
console.log(data.datas.testURL);
},
error: function (xhr, type, error) {
console.log(xhr.status + xhr.responseText);
}
});
return false;
}
Then the backend is slightly adjusted to be able to receive FormData.
Thanks for the invitation:
Token can be placed in headers, and the backend checks the token separately, while this interface only processes images