场景:在uniapp中使用uView上传组件,并在表单提交时用formData格式传输上传的文件(二进制binary格式)和其它参数

问题:uview 中的 upload 组件点击上传之后不是标准的 File 形式,点击上传单个文件之后的控制台信息如下:

[
  {
    "name": "002.jpg",
    "size": 501193,
    "thumb": "blob:http://localhost:8080/61fa2409-4084-4593-a287-dc5ffb31378c",
    "type": "image",
    "url": "blob:http://localhost:8080/61fa2409-4084-4593-a287-dc5ffb31378c"
  }
]

解决:对 file 内容进行二次加工。将生成的 blob url 地址处理成 File 文件流形式,代码如下:

this.fileList.map(async (item) => {
    const imgBlob = await fetch(item.url).then((r) => r.blob());
    let file = new File([imgBlob], item.name, { type: item.type });
    formData.append('fileList', file);
})

请求:uniapp 的 uni.request 默认不支持 formData 形式数据,所以使用 axios 进行请求,完整代码如下:

// 校验表单内容
this.$refs.uForm.validate().then(valid => {
    if (valid) {
        var formData = new FormData();  // 创建form对象
        const { typeId, transactornUserId, content, expireTime, levelId } = this.basicForm;
        formData.append('typeId', typeId);
        formData.append('transactornUserId', transactornUserId);
        formData.append('content', content);
        formData.append('expireTime', expireTime);
        formData.append('levelId', levelId);
        // 判断是否上传文件
        if (this.fileList.length>0) {
            // 文件全部格式化后再掉保存接口
            Promise.all(
                this.fileList.map(async (item) => {
                    const imgBlob = await fetch(item.url).then((r) => r.blob());
                    let file = new File([imgBlob], item.name, { type: item.type });
                    console.log(file, 'file............');
                    formData.append('fileList', file);
                })
            ).then(()=>{
                this.saveOrUpdate(formData)
            })
        }else{
            this.saveOrUpdate(formData)
        }             
    } else {
        console.log('验证失败');
    }
});

// 保存接口
saveOrUpdate(params){
    axios.post(interfaceUrl.localBase + '/saveOrUpdateTask', params, {
        headers: {
            'content-type': 'multipart/form-data',
            Authorization: getAuthorization()
        }
    }).then(res => {
        if (res.data.code == 200) {
            uni.navigateBack();
            this.$refs.uToast.show({
                message: '创建成功!',
                position: 'top',
                duration: 2000 // 持续时间 单位 ms
            });
        }else{
            this.$refs.uToast.show({
                message: '请求出错!',
                type: 'error',
                position: 'top',
                duration: 2000 // 持续时间 单位 ms
            });
        }
    }).catch(err => {
        console.log('失败了' + err.errMsg);
    })
},
最后修改:2023 年 07 月 17 日
如果觉得我的文章对你有用,请随意赞赏