//生成分割字符串
generateDivisionStr() {
return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, c => {
let r = Math.random() * 16 | 0,
v = c == 'x' ? r : (r & 0x3 | 0x8)
return v.toString(16);
})
},
//处理formdata
generateUploadParams(str,obj,type) {
let pra = ''
Object.keys(obj).forEach(key => {
//如果是ArrayBuffer类型的图片文件
if(key == "file"){
//随机图片文件名
let iName = this.generateDivisionStr()
pra += `\r\n--${str}` +
`\r\nContent-Disposition: form-data; name="${key}";filename="${iName}.png"` +
`\r\nContent-Type: "image/${type}"`+
`\r\n` +
`\r\n${obj[key]}`
}else{
pra += `\r\n--${str}` +
`\r\nContent-Disposition: form-data; name="${key}"` +
`\r\n` +
`\r\n${obj[key]}`
}
})
pra = pra + `\r\n--${str}--`
console.log(pra)
return pra
},
// 上传图片
fileUploadHandle(e,fieldprop,id,fieldtable){
let extname = e.tempFiles[0].extname;
if(extname != "png" && extname != "jpg"){
uni.showToast({
title: '图片必须为jpg或png格式',
icon: 'none',
mask: true,
duration: 2000
});
return;
}
let arrayBuffer =wx.getFileSystemManager().readFileSync(e.tempFilePaths[0]);//返回arrayBuffer
let base64=wx.getFileSystemManager().readFileSync(e.tempFilePaths[0],'base64');//返回base64
let binary=wx.getFileSystemManager().readFileSync(e.tempFilePaths[0],'binary');//返回binary
//根据自己需要的数据格式选择
let params = { file:base64,excelT:21,tableenname:fieldtable,rowid:id,fieldprop:fieldprop};
let str = this.generateDivisionStr()
let data = this.generateUploadParams(str,params,e.tempFiles[0].extname)
fileUpload(data,str).then((res) =>{
uni.showToast({
title: '上传成功',
duration: 2000
});
}).catch((err) =>{
})
},
uniapp 微信小程序 api上传图片 binary (form Data)
于 2022-05-27 17:21:15 首次发布