Friday 24 April 2020

Image uploads corrupted (Next.js, Azure Block Storage)

Hi all. I'm having trouble uploading images in my Next.js project.From my React component I'm submitting a form via these functions: const fileUpload = async (file: File) => { const url = '/api/image' const formData = new FormData() formData.append('file', file) const config = { headers: { 'content-type': 'multipart/form-data', }, } const response = await axios.post(url, formData, config) const { data } = response return data } const handleSubmit = async (event: React.SyntheticEvent) => { const url = '/api/post' if (files) { // ignore fileUpload(files[0]).then((response) => console.log('submit response', response) ) } event.preventDefault() } And the API route in Next looks like this:import formidable from 'formidable' const fs = require('fs') const { BlobServiceClient } = require('@azure/storage-blob') if (process.env.NODE_ENV !== 'production') { require('dotenv').config() } const AZURE_STORAGE_CONNECTION_STRING = process.env.AZURE_STORAGE_CONNECTION_STRING export const config = { api: { bodyParser: false, }, } const getBlobName = (originalName) => { const identifier = Math.random().toString().replace(/0\./, '') return `${identifier}-${originalName}` } export default async (req, res) => { const form = new formidable.IncomingForm() form.keepExtensions = true form.uploadDir = './public/static/uploads' form.parse(req, async (err, fields, files) => { if (err) { return } return res.json({ fields, files }) }) form.on('file', async (name, file) => { const blobServiceClient = await BlobServiceClient.fromConnectionString( AZURE_STORAGE_CONNECTION_STRING ) const containerClient = await blobServiceClient.getContainerClient( 'images' ) const buff = fs.readFileSync(file.path) const data = buff.toString('base64') const blobName = getBlobName(file.name) const blockBlobClient = containerClient.getBlockBlobClient(blobName) blockBlobClient.upload(data, data.length) }) } The image which gets stored locally is corrupt and looks like a TV tuned to a dead channel. I'm clearly not encoding it properly — but unsure whether it's my ContentType or the string encoding?​Thanks!

Submitted April 25, 2020 at 06:41AM by acpatrice

No comments:

Post a Comment