如何上传文件给接口

1.首先要确保服务器的可以正常处理formdata;

2.我们给接口的请求头应该是multipart/form-data

 可以通过这样设置

 3.如果这样设置也不行,比如目前的这个陆港项目就是这样设置也不行,那就不适用axios,使用fech;

      uploadFile(pdfData){
        let fileName = `${this.$store.state.hxydtb.WaybillId}.pdf`;
        let file = new File([pdfData],fileName, {type: "application/pdf"});
        let formData = new FormData();
        formData.append('url', file);
        fetch(window.api.baseURL +'/TBBUSIGLYDApply/uploadProject', {
          method: 'POST',
          body: formData
        })
        .then(response => response.json())
        .then(res => {
          if(res && (res.code===1001)){
            if (window.opener != null) {
              window.close();
            } else {
              // window.location.href = 'about:blank';
              // window.close();
            }
          }
          })
          .catch(error => console.error('Error:', error));
      },

因为 Axios 和 Fetch 在处理 FormData 时有所不同。在 Axios 中,你需要明确地设置 Content-Type 为 multipart/form-data。然而,当你使用 Fetch API 时,它会自动设置 Content-Type 并正确地包含一个适当的边界。

 

posted @ 2023-08-15 14:13  Eric-Shen  阅读(70)  评论(0编辑  收藏  举报