0

I'm trying to create a simple image host in Node.js, but i'm having trouble parsing form-data

The form my test application generates (to upload an image) posts the data in the following format:

----------------------8d8317fa35f1280
Content-Disposition: form-data; name="ImageUploader"; filename="Test.png"
Content-Type: image/png

<binary PNG data...>

----------------------8d8317fa35f1280--

I plan on storing the image data in a key-value database, where the key is an md5 hash of the file, and the value is the raw .png data.

I know that this is very possible with the 'express' javascript framework, but I don't wish to use any frameworks, i'm open to using a library, given that it is fast.

I would like to avoid Regex

How can I parse the filename, and the raw .png data out of this form submission data?

1 Answer 1

1

You need to use a library for parsing such data. formidable is one example, but I would recommend use multer

Example in multer,

const multer = require('multer');
const upload = multer({dest:'temp/'}) // path to a temporary folder where files will be saved

app.post('/upload', upload.single('file'), (req,res)=>{ // use middleware
    // process file here
    // file will be in req.file
})

This one is a very simple example, however multer provides very wide variety of upload methods that you should check.

For getting filename see originalname property of req.file and for reading file you need to read file req.file.path which is the actual file

Sign up to request clarification or add additional context in comments.

2 Comments

Why do you recommend multer over formidable? What are the differences
multer provides you with middleware functions which you can and you will get the file object(s) in the request obect itself. Formidable parses the form data that you have passed as input. Middlewares are cleaner and easy to use and maintan. Also multer provides you with options to set the path, filename and other properties before actually saving the file.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.