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. javascript - ueditor引入报错问题2. html5 - 响应式WEB,媒体查询的问题。3. 关docker hub上有些镜像的tag被标记““This image has vulnerabilities””4. boot2docker无法启动5. dockerfile - [docker build image失败- npm install]6. nignx - docker内nginx 80端口被占用7. docker start -a dockername 老是卡住,什么情况?8. docker容器呢SSH为什么连不通呢?9. angular.js - angular内容过长展开收起效果10. dockerfile - 为什么docker容器启动不了?

网公网安备