您的位置:首页技术文章
文章详情页

javascript - 图片上传的时候怎样把图片和字符串一起post提交到服务器?

【字号: 日期:2023-05-07 13:01:33浏览:46作者:猪猪

问题描述

上传图片的时候需要提供用户的登录令牌和需要上传的图片。但是两个不一样的数据类型怎样一起post服务器上啊!

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,没有权限} }); return false; }

问题解答

回答1:

post的data类型改成formdata,然后在formdata中装载对象,以下是例子:

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);} });回答2:

你都new出来FormData了,就别再自己攒对象了嘛,就用new出来的这个啊……

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;}

然后后端稍微调整下,能收FormData就行了。

回答3:

谢邀:

token可以放到headers中,后端单独对token做检查,而该接口只处理图片

标签: JavaScript
相关文章: