Search code examples
node.jsazure-storageazure-blob-storage

Not able to upload xlsx or csv file to azure blob storage


Want to upload XLSX or CSV file to azure. So I have created an API

http://localhost:3000/upload

Post Request using post man

This the code


app.post('/upload',(req,res)=>{
    var form = new formidable.IncomingForm();
    form.parse(req, async(err,fields,files)=> {
        const blobServiceClient = await BlobServiceClient.fromConnectionString(AZURE_STORAGE_CONNECTION_STRING);
        const containerClient = await blobServiceClient.getContainerClient('mycon');
        if(!containerClient.exists()){
            const createContainerResponse = await containerClient.create();
        }
        const blobName = files.file.name; 
        const blockBlobClient = containerClient.getBlockBlobClient(blobName);
        const uploadBlobResponse = await blockBlobClient.upload(files,files.file.size);
        console.log(files);
        res.send({message:files.file.size + "uploaded"})

    })

})

When I did console.log(files) in above code snippet

{
  file: File {
    _events: [Object: null prototype] {},
    _eventsCount: 0,
    _maxListeners: undefined,
    size: 18,
    path: 'C:\\Users\\bakhil\\AppData\\Local\\Temp\\upload_8531745c7d9ae14f105d50c775256e00',
    name: 'Book1.csv',
    type: 'application/vnd.ms-excel',
    hash: null,
    lastModifiedDate: 2020-04-01T10:03:55.885Z,
    _writeStream: WriteStream {
      _writableState: [WritableState],
      writable: false,
      _events: [Object: null prototype] {},
      _eventsCount: 0,
      _maxListeners: undefined,
      path: 'C:\\Users\\bakhil\\AppData\\Local\\Temp\\upload_8531745c7d9ae14f105d50c775256e00',        
      fd: null,
      flags: 'w',
      mode: 438,
      start: undefined,
      autoClose: true,
      pos: undefined,
      bytesWritten: 18,
      closed: false
    }
  }
}

When I am triggering the endpoint from Postman, facing the following issue:

 UnhandledPromiseRejectionWarning: Error: body must be a string, Blob, ArrayBuffer, ArrayBufferView, or a function returning NodeJS.ReadableStream.

I have no clue about the error. Please help me to resolve it.

Thanks in advance.


Solution

  • Please try by changing the following line of code:

    const uploadBlobResponse = await blockBlobClient.upload(files,files.file.size);
    

    to

    const uploadBlobResponse = await blockBlobClient.uploadFile(files.file.path);