Skip to content

Instantly share code, notes, and snippets.

@hartzis
Created July 23, 2015 05:12
Show Gist options
  • Save hartzis/fb43721affdf9acd8555 to your computer and use it in GitHub Desktop.
Save hartzis/fb43721affdf9acd8555 to your computer and use it in GitHub Desktop.
Handle Express Image File Upload
let multiparty = require('multiparty');
let fs = require('fs');
function saveImage(req, res) {
let form = new multiparty.Form();
form.parse(req, (err, fields, files) => {
let {path: tempPath, originalFilename} = files.imageFile[0];
let copyToPath = "./images/" + originalFilename;
fs.readFile(tempPath, (err, data) => {
// make copy of image to new location
fs.writeFile(newPath, data, (err) => {
// delete temp image
fs.unlink(tmpPath, () => {
res.send("File uploaded to: " + newPath);
});
});
});
})
}
@lpstandard
Copy link

Hi,

Thanks for these three snippets of code. I am now building an React app by trying to use your code. Could you give me more instructions on how to put these three files together? Thanks!

@manigk
Copy link

manigk commented Sep 15, 2017

var {path: tempPath, originalFilename} = files.imageFile[0];
      ^
SyntaxError: Unexpected token {

Please give some solutions.

@ImenTurki
Copy link

hello thank you for your code , i have an issue :

Cannot POST /upload

Failed to load resource: the server responded with a status of 404 (Not Found)

handleFileUpload(req,res) {let multiparty = require('multiparty');
       let form = new multiparty.Form();
       let fs = require('fs');

       form.parse(req, (err, fields, files) => {

           let {path: tempPath, originalFilename} = files.File[0];
           let copyToPath = "./file/" + originalFilename;
       
           fs.readFile(tempPath, (err, data) => {
           // make copy of image to new location
           fs.writeHead(200, {"Content-Type": "text/html"});
           fs.writeFile(copyToPath, data, (err) => {
               // delete temp image
               fs.unlink(tempPath, () => {
               res.send("File uploaded to: " + copyToPath);
               });
           }); 
           }); 
       })     
          
   }

the goal is to insert the uploadedfile into json object

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment