簡體   English   中英

上載沒有FormData的文件

[英]Upload file without FormData

我正在使用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() 謝謝。

這是在不包裝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!'
  }
})

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM