我有一个Node.js应用程序。在该应用中,用户可以上传文件。
const multer = require('multer')
const upload = multer({ dest: 'uploads/' })
app.put('/files/upload', upload.single('myFile'), function(req, res) {
let fileData = req.body['myFile'];
if (fileData ) {
let commaIndex = fileData.indexOf(',');
if (commaIndex !== -1) {
fileData = fileData.substr(commaIndex+1);
// Convert file data to stream here...
}
}
});
我正在尝试弄清楚如何将fileData
转换为流。我想要一个流的原因是因为我正在尝试将文件上传到Azure存储。我正在尝试使用的API([createFileFromStream][1]
)需要一个流。
谢谢!
答案 0 :(得分:1)
您想要使用的功能是fs.createReadStream()
,它允许您从文件路径中读取要传输的文件。然后,您可以使用createWriteStreamToBlockBlob
函数将流上载到Azure存储。
示例:
const express = require('express')
const multer = require('multer')
const upload = multer({ dest: 'uploads/' })
const fs = require('fs')
const azure = require('azure-storage')
const app = express()
const accountName = "yourAccountName"
const accessKey = "yourAccessKey"
const blobSvc = azure.createBlobService(accountName, accessKey)
app.post('/files/upload', upload.single('myFile'), function(req, res) {
fs.createReadStream(req.file.path).pipe(blobSvc.createWriteStreamToBlockBlob('mycontainer', req.file.originalname, function() {
res.send('Upload completed!')
}))
})