繁体   English   中英

使用 Axios put 通过 API 网关将 PDF 文件上传到 S3 存储桶

[英]Using Axios put to upload PDF files to S3 bucket via API gateway

我正在尝试将 PDF 文件上传到 React js 中的 S3 Bucket。 我通过 API 网关创建了一个 API 以公开 S3 对象的 put 方法。

当我尝试使用“put”获取方法上传文件时它工作正常,而 axios put 上传没有正文的文件。

这是我的获取代码:

function handleChange(event) {
    setFile(event.target.files[0])
  }
const handleClick = (e) => {
    e.preventDefault();
    const formData = new FormData();
    formData.append('file', file);
    const filename = file.name;
  fetch(`${PutEndPoint}/${filename}`,
  {
    method:'Put',
    headers: {
        'Content-Type': 'application/pdf',
      },
      body :formData
  
      //JSON.stringify({ title: 'Fetch PUT Request Example' })
  })
  .then(response => response.json())
  .then(json => console.log(json))

Axios代码:

function handleChange(event) {
    setFile(event.target.files[0])
  }
const handleClick = (e) => {
    e.preventDefault();
    const formData = new FormData();
    const filename = file.name;
    console.log(file.name);
    formData.append('file', file);
    console.log(formData)
   
  axios(`${PutEndPoint}/${filename}`,
  {
    method:'Put'
    headers: {
        'Content-Type': 'application/pdf',
      },
      formData
    })
  .then(response => response.json())
  .then(json => console.log(json))

HTML:

  <input type='file' name="file" onChange={handleChange}></input>
    <Button onClick= {handleClick}>
      Upload
  </Button>

我努力了:

  1. 使用 content-type 作为 multipart/form-data
  2. 从 header 中删除 content-Type
  3. 将文件名作为第三个参数添加到 append
     formData.append('file', file, file.name);
  4. 更改 API 的 content-type 以接受 multipart/form-data

这些都没有奏效。

根据文档,语法必须如下所示:

// Send a PUT request
axios({
  method: 'put', // the request method to be used when making the request request
  url: '`${PutEndPoint}/${filename}`', // the server URL that will be used for the request,
  headers: {'Content-Type': 'application/pdf'}, // custom headers to be sent
  data: formData // --> the data to be sent as the request body
});

// data是要作为请求体发送的数据
// 仅适用于请求方法“PUT”、“POST”、“DELETE”和“PATCH”
// 当没有设置transformRequest时,必须是以下类型之一:
// - 字符串,普通 object,ArrayBuffer,ArrayBufferView,URLSearchParams
// - 仅限浏览器:FormData、File、Blob
// - 仅节点:Stream,缓冲区

https://github.com/axios/axios#axios-api

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM