m0_56756522 2025-04-29 15:27 采纳率: 21.4%
浏览 37

uni开发h5为什么我给后端传递的文件后端收不到呢,会报错400文件上传失败


chooseImge() {
                let that = this
                uni.chooseImage({
                    count: 1, //默认9
                    success: (res) => {
                        that.avatar = res.tempFilePaths[0];
                        console.log(that.avatar)
                        uni.uploadFile({
                            url: '',
                            filePath: that.avatar,
                            name: 'file',
                            formData: {
                                type: "avatar",
                                file: res.tempFilePaths[0]
                            },
                            header: {
                                "Content-Type": "application/x-www-form-urlencoded",
                                'Authorization': 'Bearer ' + uni.getStorageSync('token'),
                                'Access-Control-Allow-Origin': '*',
                                'Access-Control-Allow-Credentials': true,
                                'Access-Control-Allow-Methods': '*',
                                'Access-Control-Allow-Headers': '*'
                            },
                            success: (uploadFileRes) => {
                            }
                        });
                    }
                })
                console.log(this.loadingimg)
            }   
  • 写回答

4条回答 默认 最新

  • 阿里嘎多学长 2025-04-29 15:27
    关注

    阿里嘎多学长整理AIGC生成,因移动端显示问题导致当前答案未能完全显示,请使用PC端查看更加详细的解答过程

    uni开发h5为什么我给后端传递的文件后端收不到呢,会报错400文件上传失败

    你在使用uni-app的chooseImage方法选择图片后,想要将图片传递给后端,但是后端却收不到文件,报错400文件上传失败。

    可能的原因是:

    1. 文件名或路径不正确
    2. 文件大小超过了后端的限制
    3. 文件类型不正确
    4. 传递文件的方式不正确

    解决方案:

    1. 检查文件名或路径是否正确,确保后端可以正确地解析文件名。
    2. 检查文件大小是否超过了后端的限制,确保文件大小在允许的范围内。
    3. 检查文件类型是否正确,确保文件类型是允许的类型。
    4. 使用uni.uploadFile方法将文件传递给后端,例如:
    chooseImge() {
      let that = this
      uni.chooseImage({
        success: (res) => {
          const filePath = res.tempFilePaths[0]
          uni.uploadFile({
            url: '你的后端上传接口',
            filePath,
            name: 'file',
            header: {
              'Content-Type': 'multipart/form-data'
            },
            success: (res) => {
              console.log(res.data)
            }
          })
        }
      })
    }
    

    在上面的代码中,我们使用uni.uploadFile方法将选择的图片文件传递给后端,设置了文件名、header和success回调函数。

    评论

报告相同问题?

问题事件

  • 创建了问题 4月29日