Giter Club home page Giter Club logo

multer's Introduction

Route middleware for Koa that handles multipart/form-data using multer

NPM version NPM Downloads Build status Test coverage Dependency status License

Call for Maintainers

This module is a fork of koa-multer, the most widely used multer middleware in the koa community. Due to lack of maintenance, it was forked to the official Koa organization and is available under @koa/multer package name.

Install

Note that you must install either [email protected] (Buffer) or [email protected] (Streams):

npm install --save @koa/multer multer

Usage

const Koa = require('koa');
const Router = require('@koa/router');
const multer = require('@koa/multer');

const app = new Koa();
const router = new Router();
const upload = multer(); // note you can pass `multer` options here

// add a route for uploading multiple files
router.post(
  '/upload-multiple-files',
  upload.fields([
    {
      name: 'avatar',
      maxCount: 1
    },
    {
      name: 'boop',
      maxCount: 2
    }
  ]),
  ctx => {
    console.log('ctx.request.files', ctx.request.files);
    console.log('ctx.files', ctx.files);
    console.log('ctx.request.body', ctx.request.body);
    ctx.body = 'done';
  }
);

// add a route for uploading single files
router.post(
  '/upload-single-file',
  upload.single('avatar'),
  ctx => {
    console.log('ctx.request.file', ctx.request.file);
    console.log('ctx.file', ctx.file);
    console.log('ctx.request.body', ctx.request.body);
    ctx.body = 'done';
  }
);

// add the router to our app
app.use(router.routes());
app.use(router.allowedMethods());

// start the server
app.listen(3000);

Contributors

Name Website
Nick Baugh http://niftylettuce.com/
Imed Jaberi https://www.3imed-jaberi.com/

License

MIT © Fangdun Cai

multer's People

Contributors

3imed-jaberi avatar alincode avatar dependabot[bot] avatar fundon avatar i5ting avatar linusu avatar mcfizh avatar niftylettuce avatar titanism avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar

multer's Issues

TypeScript definitions of this fork

I'm terribly sorry if this is blatantly obvious, but I'm having trouble finding the TypeScript definitions for this fork. Are there any available, and if so, could someone do me a huge favor and point me in the right direction?

Cheers!

Error in npm README

There is a small typo in the README on the npm page. The install line is
npm install --save koa/multer multer (missing @) instead of
npm install --save @koa/multer multer.

Suggest: move module "multer" into dependencies from peerDependencise(or devDependencies) ?

Discuss: Move module "multer" into dependencies from devDependencise and peerDependencies.

npm WARN @koa/[email protected] requires a peer of multer@* but none is installed. You must install peer dependencies yourself.

The warning via the console.warn is easily overlooked.

index.js

/**
 * Module dependencies.
 */

const originalMulter = require('multer');

package.json

//...
"peerDependencies": {
  "multer": "*"
},
"dependencies": {},
"devDependencies": {
  //...
  "multer": "^1.3.0",
  //...

multer options storage has no effect

Hello, it seems to me that this multer version doesn't take the storage option.
I'm using strapi as backend which uses koajs under the hood.

var multer = require('@koa/multer');
const path = require('path');

 const storage = multer.diskStorage({
  destination: function (req, file, cb) {
    console.log('TEST!');
    cb(null, path.resolve(__dirname, './public'));
  },
  filename: function (req, file, cb) {
   console.log('TEST2222!');
    let fileName = file.originalname.toLowerCase();
    let fileExtension;

    if (fileName.endsWith('.jpg')) {
      fileExtension = '.jpg';
    } else if (fileName('.png')) {
      fileExtension = '.png'
    }
    cb(null, file.fieldname + '-' + Date.now() + fileExtension)
  }
});

const upload = multer({ storage: storage });

module.exports = {
  handleUpload: async ctx => {
    console.log(__dirname);
    console.log('upload files ');
    await upload.single('upload')(ctx, demo123 => {
      console.log('ctx.request.files', ctx.request.files);
      console.log('ctx.files', ctx.files);
      ctx.body = 'done';
    });

    ctx.send('Hello World!' + JSON.stringify(ctx));
  },
};

Assume that this is a POST request with formdata e.g.

    <form action="http://localhost:1337/customupload" method="POST" enctype="multipart/form-data">
        <input type="file" name="upload" />
        <button type="submit">send</button>
    </form>

I get the following log:

D:\dev\custom-editor-strapi\my-app\api\custom\controllers
upload files 
=======================
ctx.request.files { upload:
   File {
     _events: [Object: null prototype] {},
     _eventsCount: 0,
     _maxListeners: undefined,
     size: 2577192,
     path:
      'C:\\Users\\kevin\\AppData\\Local\\Temp\\upload_a0c1a8b2879fe36b3025df6d794c70ae',
     name: 'bread-delicious-egg-704569.jpg',
     type: 'image/jpeg',
     hash: null,
     lastModifiedDate: 2019-10-30T15:21:47.475Z,
     _writeStream:
      WriteStream {
        _writableState: [WritableState],
        writable: false,
        _events: [Object: null prototype] {},
        _eventsCount: 0,
        _maxListeners: undefined,
        path:
         'C:\\Users\\kevin\\AppData\\Local\\Temp\\upload_a0c1a8b2879fe36b3025df6d794c70ae',
        fd: null,
        flags: 'w',
        mode: 438,
        start: undefined,
        autoClose: true,
        pos: undefined,
        bytesWritten: 2577192,
        closed: true } } }
ctx.files undefined

Use of `fix-esm` seems to break the `tsx`

I am using tsx for autoreload of dev server, but as soon as I install @koa/multer, I get this error:

TypeError: Cannot assign to read only property '.mjs' of object '[object Object]'

Similar to the one reported here: privatenumber/tsx#230

It seems the culprit is this line here: let originalMulter = require('fix-esm').require('multer');

So my question is - why is the fix-esm module required here and can this be fixed from your side?

Versions:

  • node: 20.8.1
  • @koa/multer: 3.0.2

Uploading a large file

Hi,

Trying to upload a 2GB file, getting 413.

Here's my config, is that correct?

const upload = multer({
  dest: publicRoot,
  limits: {
    fileSize: 10*1024*1024*1024
  }
});

Later:

router.post('/share', async (ctx, next) => {
  if (ctx.query.secret != config.secret) {
    ctx.throw(403);
  }
  await next();
}, upload.single('file'), ctx => {
  ...
});

P.S. looks like a 200mb file also fails, while 50mb is ok.

large file uploads?

Does this support large file uploads? 2GB file size?

I want to show an indicator in UI and save the file to disk.

Make it more convient to access context

I need to access the koa router params in multer storage filename option, but the filename option only provides request argument, event It is not the same as context.request. I use the following code to access context.params. Is there a better solution?

let tempUserIdParam;
// upload avatar
const avatarStorage = multer.diskStorage({
    destination: resolvePath(projectRoot, './public/images/avatar'),
    filename(req, file, cb) {
       // req is different from context.request
        cb(null, `${tempUserIdParam}${path.extname(file.originalname)}`);
    },
});
const multerForAvatar = multer({ storage: avatarStorage });
const uploadAvatar = compose([
    async (ctx, next) => {
        const schema = Joi.object({ id: Joi.string().required() });
        await ctx.validateAsync(schema, 'params');
        tempUserIdParam = ctx.params.id;
        await next();
    },
    multerForAvatar.single('avatar'),
    async (ctx, next) => {
        ctx.restify({}, 'update avatar success!');
        await next();
    },
]);

[help] It doesn't parse my form :(

I want to parse my form using @koa/multer + koa-router but it doesn't seem to be working.

Here's the form code:

<form>
  <h1>Drag your project here</h1><label for="files" tabindex="0">
  <div>Drag n drop some files or click to call menu</div></label>
  <input type="file" name="files" id="files" multiple="" style="display:none" autocomplete="off" tabindex="-1">
</form>

And request payload:

-----------------------------185150583314124597231842462796
Content-Disposition: form-data; name="name"

useful-steel
-----------------------------185150583314124597231842462796
Content-Disposition: form-data; name="files"; filename=""
Content-Type: application/octet-stream


-----------------------------185150583314124597231842462796--

Code:

  router.post(
    '/api/upload',
    upload.fields([
      {
        name: 'name',
        maxCount: 1
      },
      {
        name: 'files',
        maxCount: 600000
      }
    ]),
    ctx => {
      console.log(ctx.request.files)
      console.log(ctx.files)
      ctx.body = 'Done.'
    }

Console output:

DirHub on  master [✘!] is 📦 v1.0.0 via ⬢ v12.8.1 
➜ yarn dev
yarn run v1.17.3
$ node -r esm index
> Using external babel configuration
> Location: "/home/v1rtl/Desktop/Coding/DirHub/.babelrc"
[ ready ] compiled successfully
[ wait ]  compiling ...
Listening on http://192.168.241.13:3000
[ ready ] compiled successfully
[ event ] client pings, but there's no entry for page: /
[ event ] build page: /
[ wait ]  compiling ...
[ event ] build page: /next/dist/pages/_error
[ ready ] compiled successfully
[Object: null prototype] {}
[Object: null prototype] {}
[ event ] client pings, but there's no entry for page: /_error
[ event ] disposing inactive page(s): /next/dist/pages/_error
[Object: null prototype] {}
[Object: null prototype] {}

curl output:

➜ curl -X POST -F "name=hi"  http://192.168.241.13:3000/api/upload
Done.⏎  

and the same in console

I use Next.js + Koa custom server

Here's my package.json:

{
  "dependencies": {
    "@koa/multer": "^2.0.0",
    "get-port": "^5.0.0",
    "ip": "^1.1.5",
    "koa": "^2.8.1",
    "koa-router": "^7.4.0",
    "koa-send": "^5.0.0",
    "mongodb": "^3.3.0",
    "multer": "^1.4.2",
    "next": "^9.0.4",
    "open": "^6.4.0",
    "project-name-generator": "^2.1.7",
    "react": "^16.9.0",
    "react-dom": "^16.9.0",
    "react-dropzone": "^10.1.7",
    "react-markdown": "^4.1.0",
    "react-router-dom": "^5.0.1",
    "rebass": "3.1.1",
    "styled-components": "^4.3.2"
  },
  "scripts": {
    "dev": "node -r esm index"
  },
  "name": "dirhub-frontend",
  "version": "1.0.0",
  "description": "frontend for DirHub",
  "main": "index.js",
  "repository": "https://github.com/talentlessguy/PassSyncFrontend.git",
  "author": "talentlessguy <[email protected]>",
  "license": "MIT",
  "devDependencies": {
    "@babel/core": "^7.5.5",
    "@babel/preset-env": "^7.5.5",
    "@babel/preset-react": "^7.0.0",
    "babel-eslint": "^10.0.2",
    "babel-plugin-styled-components": "^1.10.6",
    "eslint": "^6.1.0",
    "eslint-config-prettier": "^6.0.0",
    "eslint-plugin-prettier": "^3.1.0",
    "eslint-plugin-react": "^7.14.3",
    "esm": "^3.2.25",
    "nodemon": "^1.19.1",
    "prettier": "^1.18.2"
  }
}

How to upload a file? Example, KoaBody, Multer, Koa Router

Hi, I'm trying to configure Multer to upload images and store them on my disk, but I can't find an example with KoaRouter, KoaBody and Multer, to be honest, I'm very confused, in the documentation of this repo I don't find "real" examples.
How do I upload the file received from a form?
How do I get the final path of the stored file?

const koaRouter = require('koa-router');
const koaBody = require('koa-body');
const multer = require('@koa/multer');
const IMG_DIR = require("../../auth/dir.js");

// EndPoint
const route = new koaRouter({ 
    prefix: '/products' 
});

// Multer
const upload = multer({
    dest: IMG_DIR        // c://exampleRoute/app/public/images
});

route.post('/add', koaBody({ multipart: true }), async (context) => {
    try {
       // For get the file?
        console.log(context.request.files);
       // Upload?
        upload.single(context.request.files.img1);
    } catch (error) {
        console.log(error.message);
        context.body = { error: true, message: error };
    }
});

File uploaded but ctx does not have response

Hi guys, have been looking around for solutions but have been stuck with this problem for sometime with no idea how to come about.

I am able to upload files to my local drive, as i can see the files being created in the destination folder, however, the response that i get from the ctx was 404 and there was no body.

Here is my HTML

 <form action="http://localhost:3000/api/image/upload" enctype="multipart/form-data" method="POST">
    <input type="file" name="myFile" />
    <input type="hidden" name="incomingIP" value="10.20.30.40" />
    <input type="submit" value="Upload a file" />
  </form>

And my js (route.js)

import Router from 'koa-router';
import multer from 'koa-multer';

const router = new Router({ prefix: '/api/image' });

const storage = multer.diskStorage({
    destination: function (req, file, cb) {
        cb(null, process.env.FILES_UPLOAD_DIR)  
    },
    filename: function (req, file, cb) {
        let fileFormat = (file.originalname).split(".");
        cb(null,Date.now() + "." + fileFormat[fileFormat.length - 1]);
    }
})

router.post('/upload', upload.any(), async ctx =>{
    console.log(ctx);
});

export default router;

And here is the part which i cant figure out; the printed ctx was

{
  request: {
    method: 'POST',
    url: '/api/image/upload',
    header: {
      host: 'localhost:3000',
      connection: 'keep-alive',
      'content-length': '34019',
      'cache-control': 'max-age=0',
      origin: 'http://localhost:3000',
      'upgrade-insecure-requests': '1',
      'content-type': 'multipart/form-data; boundary=----WebKitFormBoundary9rMTCRZ78y5G4146',
      'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.88 Safari/537.36',
      'sec-fetch-user': '?1',
      accept: 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9',
      'sec-fetch-site': 'same-origin',
      'sec-fetch-mode': 'navigate',
      referer: 'http://localhost:3000/api/image',
      'accept-encoding': 'gzip, deflate, br',
      'accept-language': 'en-US,en;q=0.9',
      cookie: ''
    }
  },
  response: {
    status: 404,
    message: 'Not Found',
    header: [Object: null prototype] {
      'content-type': 'text/plain; charset=utf-8',
      'content-length': '9'
    }
  },
  app: { subdomainOffset: 2, proxy: false, env: 'development' },
  originalUrl: '/api/image/upload',
  req: '<original node req>',
  res: '<original node res>',
  socket: '<original node socket>'
}

How could i get the file and the body that was sent from the ctx ?

Am i missing something?

Any help will be greatly appreciated.

Missing Files

I see that is missing some files, for example:

  • History.md || CHANGELOG.md
  • Authors.md
  • CODE_OF_CONDUCT.md
  • CONTRIBUTING.md

@niftylettuce, what do you think 🤔?

Usage with Typescript

👋

I've searched for types definition about this package, but the only one available is about the previous version of koa-mutlter.

Do you plan to provide type definitions in a near future ?

Thx :)

Bug: Cannot Find Module 'multer'

Bug Report

Current Behavior
"Error: Cannot find module 'multer'" after updating to 3.0.2. Prior to updating koa/multer, I was using v3.0.0 without any issues. We use webpack for bundling. It looks like the issue has to do with webpack and the use of fix-esm which was introduced in v3.0.2. Any thoughts / ideas on how to get this working? Thanks!

Environment

  • Node/npm/yarn version: Node 12 yarn v3.1.1
  • @koa/multer & koa version: @koa/multer 3.0.2

Additional context/Screenshots
image

Bug: I can't start my compiled project because of multer.

Bug Report

Current Behavior
I can successfully compile my project with webpack. However, I can not start the compiled js file with the node order. And every time I do this node service.cjs, there will occur the error message: "Cannot find module 'multer'".

Input Code
- REPL or Repo link if applicable:

Expected behavior/code
I hope that I can run the compiled js file.

Additional context/Screenshots
Add any other context about the problem here. If applicable, add screenshots to help explain.
image

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.