代码之家  ›  专栏  ›  技术社区  ›  daviestar

上载不带FormData的文件

  •  0
  • daviestar  · 技术社区  · 7 年前

    我正在使用 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)
    }
    

    对于本地开发和测试,我想在节点中创建一个路由。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节点。js服务器,无需包装 FormData() ?谢谢

    1 回复  |  直到 7 年前
        1
  •  2
  •   daviestar    7 年前

    下面是如何在不包装的情况下上载文件 FormData() 在Koa:

    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!'
      }
    })