我正在使用 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!'
}
})
关于javascript - 上传没有 FormData 的文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50017981/