Javascript 上载不带FormData的文件

Javascript 上载不带FormData的文件,javascript,node.js,koa,Javascript,Node.js,Koa,我正在使用XMLHttpRequest将大型文件从浏览器直接上传到AmazonS3,如下所示(有效): 对于本地开发和测试,我想在node.js服务器中创建一个路由,它将接受像这样的上传文件 服务器端,request.body始终为空: router.put('/image-upload', koaBody(), async (ctx) => { console.log(ctx.request) // { method: 'PUT', // url: '/image-uplo

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

对于本地开发和测试,我想在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的
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!'
  }
})

这个包看起来很有趣,而不是自己做:从客户端来看,这个过程应该与您在其他地方使用的过程相同。因此,我不知道为什么要更改URL以外的任何代码(例如,为什么要使用该内容类型?!)如果您询问服务器端,请提供一个。为什么会投反对票?我在解释我的问题,以及我试图解决的问题。
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!'
  }
})