javascript - 图片上传的时候怎样把图片和字符串一起post提交到服务器?
问题描述
上传图片的时候需要提供用户的登录令牌和需要上传的图片。但是两个不一样的数据类型怎样一起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做检查,而该接口只处理图片
相关文章:
1. mac里的docker如何命令行开启呢?2. angular.js - AngularJS中的$scope的作用相当于android中的适配器一样,这种描述准确吗?3. node.js - 微信第三方平台网页授权scope没有权限4. angular.js - angularjs怎么实现跳转的,是要写路由吗5. Angular.js 无法设置Authorization头,该怎么解决?6. javascript - 前端怎么展示这种类型的数据?7. css - 移动端 oppo 手机之 Border-radius8. javascript - 关于圣杯布局的一点疑惑9. PHP单例模式10. PHP中的$this代表当前的类还是方法?