【问题标题】:file Upload causing issues other than PDF files文件上传导致 PDF 文件以外的问题
【发布时间】:2020-06-12 09:45:00
【问题描述】:
const uploadData = new FormData();
      uploadData.append("engfile",fileObj.originFile);
const [response,error] = yield call(() => fetch(`http://localhost:44361/api/v1/files?fileName=${payload.name}&fileSize=${payload.size}`, {
        method: 'POST',
        body: uploadData,
        headers:{
             'Content-Type':'multipart/form-data;',
             'token':'token'
        }
      })
       .then((response) => response.json())
      .then((result) => {
        console.log('Success:', result);
        // yield put({type:"UPLOAD_SUCCESS",data:response.data})
        return result;
      })
      .catch((error) => {
        return error;
      }));

我正在尝试将文件从 UI 上传到服务器,但上面的代码非常适合 PDF 文件,但如果我在浏览器中发送 .docx 或图像文件,因为 .docX 和 .xlsx 文件是可写的,文件会得到均匀的边界值与内容类型。如何使用 fetch API 避免这种情况?

上面的代码非常适合pdf文件,因为它不可写,但对于其他文件则不能,如何在UI级别解决这个问题,或者我们是否必须在API级别(API端的nodejs)处理,可以请你在这里指导我?

在 PDF 浏览器请求中:

【问题讨论】:

  • ` 文件获取边界值和内容类型` 你是什么意思?
  • 我的意思是,正如您在屏幕截图中看到的内容类型/元数据被写入有效负载中,我应该如何避免它?或者我不能从 UI ?除了 PDF 文件,我还需要一些正确的东西

标签: javascript node.js reactjs pdf file-upload


【解决方案1】:

我认为您不应该覆盖 Content-Type 标头,因为内部浏览器设置了 boundary

Content-Type: multipart/form-data; boundary=----WebKitFormBoundaryUpNj05W8fQrQrefK

示例:当您运行此程序并查看网络面板时,提到的标题已设置

const formData = new FormData();

const testFile = new Blob([], {
  type: 'text/plain'
})

formData.append("testFile", testFile)

console.log([...formData.entries()])

fetch("/test", {
  method: 'POST',
  body: formData
}).catch(error => {

});

【讨论】:

  • 是的,你是对的,为什么代码 sn-p 结果中的大小为 0 ("size": 0,)?
  • 我创建了空 blob 用于演示目的。
猜你喜欢
  • 2019-10-09
  • 2015-08-22
  • 2014-03-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-12-02
  • 1970-01-01
  • 2016-03-28
相关资源
最近更新 更多