我正在使用nodejs和express4。我有一个form-post方法(文件上传为base64),我将此文件保存到带有流的gridfs。
这是我的代码:
exports.transcribe = function (gridfs, req, res) {
const buffer = Buffer.from(req.body.file.split(';base64,')[1], 'base64')
let contentType = req.body.file.split(';base64,')[0].replace('data:', '')
streamifier.createReadStream(buffer).pipe(gridfs.createWriteStream({
filename: uuid.v4() + '.txt',
content_type: contentType,
metadata: {
user: req.user
}
}))
// this is request-promise-native
request.post({
headers: {
'Content-Type': 'multipart/form-data'
},
uri: process.env.REST_ENDPOINT,
// stream is created with streamifier from a buffer object
formData: {'file': streamifier.createReadStream(buffer)}
}).then(console.log).catch(console.error)
res.status(200).json({file: file, user: req.user})
}
代码在执行同步时有效,但它不在请求处理中。
我读到可能在我发送之前流已被取消。 缺少的是文件的内容。请求本身已执行。
**编辑**
好的,我能够解决这个问题。我不再使用这些流了:
exports.transcribe = function (gridfs, req, res) {
const buffer = Buffer.from(req.body.file.split(';base64,')[1], 'base64')
let contentType = req.body.file.split(';base64,')[0].replace('data:', '')
streamifier.createReadStream(buffer).pipe(gridfs.createWriteStream({
filename: uuid.v4() + '.txt',
content_type: contentType,
metadata: {
user: req.user
}
}))
request.post(process.env.REST_ENDPOINT, {
headers: {
'Content-Type': 'multipart/form-data'
},
formData: {
'file': {
value: buffer,
options: {
filename: 'transcribeme.txt',
contentType: contentType
}
}
}
}).then((data) => {
console.log(data)
res.status(200).json({user: req.user})
}).catch((err) => {
console.error(err)
res.status(500).json({user: req.user})
})
}
答案 0 :(得分:0)
好的,我能够解决此问题。我不再使用流了:
exports.transcribe = function (gridfs, req, res) {
const buffer = Buffer.from(req.body.file.split(';base64,')[1], 'base64')
let contentType = req.body.file.split(';base64,')[0].replace('data:', '')
streamifier.createReadStream(buffer).pipe(gridfs.createWriteStream({
filename: uuid.v4() + '.txt',
content_type: contentType,
metadata: {
user: req.user
}
}))
request.post(process.env.REST_ENDPOINT, {
headers: {
'Content-Type': 'multipart/form-data'
},
formData: {
'file': {
value: buffer,
options: {
filename: 'transcribeme.txt',
contentType: contentType
}
}
}
}).then((data) => {
console.log(data)
res.status(200).json({user: req.user})
}).catch((err) => {
console.error(err)
res.status(500).json({user: req.user})
})
}