【JS】Vue图片上传
使用的vant插件上传图片,回调返回的是base64信息,在此基础上请求接口上传
-
base64转file
-
formData
-
multipart/form-data + post
-
withCredentials 跨域请求设置
function base64ToFile(urlData, fileName) {
let arr = urlData.split(',');
let mime = arr[0].match(/:(.*?);/)[1];
let bytes = atob(arr[1]); // 解码base64
let n = bytes.length
let ia = new Uint8Array(n);
while (n--) {
ia[n] = bytes.charCodeAt(n);
}
return new File([ia], fileName, { type: mime });
}
// base64转file
let filePath = base64ToFile(file.content, '图片名称')
// formdata提交
let param = new FormData();
param.append('file', filePath);
param.append('data', pramas.data);
param.append('verify', pramas.verify);
// 请求
axios({
filePath: filePath,
method: 'post',
url: CONFIG.uploadUrl + 'images/upload',
headers: {
'Content-Type': 'multipart/form-data'
},
responseType: 'json',
withCredentials: true,
data: param,
}).then ...
Content-Type四种常见取值
-
application/x-www-form-urlencoded :最常见 POST 提交数据的方式。浏览器的原生 form 表单,如果不设置 enctype 属性,那么最终就会以 application/x-www-form-urlencoded 方式提交数据。
-
multipart/form-data :另一种非常常见的 POST 数据提交的方式。我们在使用表单上传文件时,必须让 form 的 enctyped 等于这个值。
-
application/json :可以方便的提交复杂的结构化数据,特别适合 RESTful 的接口;也有些服务端语言还没有支持这种方式,例如 php 就无法通过 $POST 对象获得内容。这时候,需要自己动手处理下:在请求头中 Content-Type 为 application/json 时,从 php://input 里获得原始输入流,再 jsondecode 成对象。
得意时做事,失意时读书

浙公网安备 33010602011771号