Skip to content

Instantly share code, notes, and snippets.

@abhishekr700
Last active December 13, 2019 20:29
Show Gist options
  • Save abhishekr700/c9776488616aa5fe41bbbca0791eeea0 to your computer and use it in GitHub Desktop.
Save abhishekr700/c9776488616aa5fe41bbbca0791eeea0 to your computer and use it in GitHub Desktop.

Link

https://www.npmjs.com/package/express-fileupload

Install

npm install --save express-fileupload

How to use

  1. Set Middleware in app.js/server.js

    // Process file uploads
    const fileupload = require("express-fileupload");
    
    app.use(fileupload({
        safeFileNames: true,
        createParentPath: true,
        preserveExtension: 4
    }));
    
    
  2. When you upload a file, the file will be accessible from req.files our input's name field is foo: <input name="foo" type="file" /> In your express server request, you can access your uploaded file from req.files.foo.
    The req.files.foo object will contain the following:

    • req.files.foo.name: "car.jpg"
    • req.files.foo.mv: A function to move the file elsewhere on your server
    • req.files.foo.mimetype: The mimetype of your file
    • req.files.foo.data: A buffer representation of your file, returns empty buffer in case useTempFiles option was set to true.
    • req.files.foo.tempFilePath: A path to the temporary file in case useTempFiles option was set to true.
    • req.files.foo.truncated: A boolean that represents if the file is over the size limit
    • req.files.foo.size: Uploaded size in bytes
    • req.files.foo.md5: MD5 checksum of the uploaded file
  3. Move the uploaded file somewhere using .mv() .

    // Move file to location
    await file.mv("/home/user/mypro/downloads");
    
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment