【问题标题】:Upload file without FormData上传没有 FormData 的文件
【发布时间】:2018-04-25 08:54:35
【问题描述】:

我正在使用XMLHttpRequest 将大文件从浏览器直接上传到 Amazon S3,如下所示(有效):

export const fileUploader = async (url, file) => {
  const xhr = new XMLHttpRequest()

  xhr.upload.addEventListener('load', () => {
    // ...
  })
  xhr.upload.addEventListener('error', () => {
    // ...
  })
  xhr.upload.addEventListener('abort', () => {
    // ...
  })
  xhr.upload.addEventListener('progress', () => {
    // ...
  })

  xhr.open('PUT', url)
  xhr.setRequestHeader('content-type', file.type)
  xhr.setRequestHeader('x_file_name', file.name)
  xhr.send(file)
}

对于本地开发和测试,我想在我的 node.js 服务器中创建一个路由,它将接受像这样上传的文件。

服务器端,request.body 始终为空:

router.put('/image-upload', koaBody(), async (ctx) => {
  console.log(ctx.request)

  // { method: 'PUT',
  // url: '/image-upload',
  // header:
  //  { host: 'localhost:3500',
  //    connection: 'keep-alive',
  //    'content-length': '324285',
  //    pragma: 'no-cache',
  //    'cache-control': 'no-cache',
  //    origin: 'http://localhost:3000',
  //    'user-agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.10 Safari/537.36',
  //    x_file_name: 'l1lnRw.jpg',
  //    'content-type': 'image/jpeg',
  //    accept: '*/*',
  //    referer: 'http://localhost:3000/gallery/4',
  //    'accept-encoding': 'gzip, deflate, br',
  //    'accept-language': 'en-US,en;q=0.9,fr;q=0.8' } }


  console.log(ctx.request.body) // {}
  console.log(ctx.req.body) // undefined
})

如何将文件“直接”上传到 Koa node.js 服务器而不将其包装在 FormData() 中?谢谢。

【问题讨论】:

  • 这个包看起来很有趣,而不是自己做:npmjs.com/package/s3rver
  • 从客户端,该过程应该与您在其他地方使用的相同。所以我不知道你为什么要更改除 URL 之外的代码的任何内容(例如,你为什么使用该内容类型?!)
  • 如果您询问服务器端,请提供minimal reproducible example
  • 为什么投反对票?我正在解释我的问题,以及我试图解决的问题。

标签: javascript node.js koa


【解决方案1】:

这是在 Koa 中上传文件而不用 FormData() 包装的方法:

import getRawBody from 'raw-body'

router.put('/image-upload', async (ctx) => {
  const file = await getRawBody(ctx.req)
  const bufferStream = new stream.PassThrough()
  const writeStream = fs.createWriteStream(`${config.staticDir}/file.jpg`)
  bufferStream.end(file)
  bufferStream.pipe(writeStream)

  ctx.body = {
    status: 'uploaded!'
  }
})

【讨论】:

    猜你喜欢
    • 2014-11-16
    • 2015-01-16
    • 1970-01-01
    • 2023-04-06
    • 1970-01-01
    • 1970-01-01
    • 2017-08-30
    • 2017-09-06
    • 1970-01-01
    相关资源
    最近更新 更多