1

I have a Node.js app. In that app, a user can upload a file.

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...
    }
  }
});

I'm trying to figure out how to convert the fileData to a stream. The reason I want a stream is because I'm trying to upload the file to Azure Storage. The API I'm trying to use ([createFileFromStream][1]) requires a stream.

Thank you!

user70192
  • 13,786
  • 51
  • 160
  • 240
  • Duplicate of https://stackoverflow.com/questions/18317904/stream-uploaded-file-to-azure-blob-storage-with-node? – qux Jun 08 '17 at 18:17
  • @qux I don't see how this is a duplicate. I just reviewed that question and I believe my approach is different. – user70192 Jun 08 '17 at 19:44

1 Answers1

2

The function you would want to use is fs.createReadStream() which allows you to read a file to stream from the file path. And then you can use createWriteStreamToBlockBlob function to upload a stream to Azure Storage.

Example:

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

})
Aaron Chen
  • 9,835
  • 1
  • 16
  • 28
  • Is this more recommended over the answer here, which uses a "new Readable" and "push(binary)" instead? https://stackoverflow.com/a/54136803/228369 – chrismarx Sep 09 '19 at 12:58