问题背景:
微信小程序内没有FormData这个对象,FormData针对的web,
我们通常会这样来进行图片的接口传输。
<script>
let fd = new FormData();
fd.append("file", itemFile);
</script>
然后把fd作为参数进行传输。
在uni-app内,提供了一个uni.uploadFile的方法,可以把获取到的临时的文件url来进行传输, 然后就可以实现文件的上传功能了。
解决方法:
//1.通过uni-file-picker的@select的方法返还tempFiles和tempFilePaths字段。
<view class="example-body">
<uni-file-picker @select="selectVal" limit="5" file-mediatype="all" title="最多选择5个文件"></uni-file-picker>
</view>
<script>
const selectVal = (file) => {
console.log(file.tempFiles, file.tempFilePaths);
}
//调用uploadFile方法来进行图片的转换。
uni.uploadFile({
url: `${BASE_URL}/api/uploadFile`, //需要传图片的后台接口
filePath: tempFilePaths[0], // 上传图片 通过uni-app的uni-file-picker组件 函数返回
name: 'file', //文件名字
header: {
'Authorization': "Bearer " + '1234567890',//token
},
formData: {
type: Object,
default() {
return {};
}
},
success: res => {
console.lo(res)
},
fail: e => {
console.log(e)
}
});
</script>