koajs / multer Goto Github PK
View Code? Open in Web Editor NEWMiddleware for handling `multipart/form-data` for koa, based on Express's multer.
License: MIT License
Middleware for handling `multipart/form-data` for koa, based on Express's multer.
License: MIT License
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.
๐
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 :)
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 };
}
});
Does this support large file uploads? 2GB file size?
I want to show an indicator in UI and save the file to disk.
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.2Can somebody explain to me how to use koa-multer with file stream?
I would like to use filestream to know whether file size is above the limit or not and maybe to pipe it to the storage server.
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();
},
]);
The link is not redirecting correctly.
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.
I see that is missing some files, for example:
@niftylettuce, what do you think ๐ค?
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
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
.
fix-esm package uses @babel/[email protected]: This proposal has been merged to the ECMAScript standard and thus this plugin is no longer maintained.
By default, Multer stores the file data stream in memory and writes the file once it has received all the data from the client ?
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.
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
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",
//...
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"
}
}
Should update the nodejs versions like here in koa.
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!
A declarative, efficient, and flexible JavaScript library for building user interfaces.
๐ Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. ๐๐๐
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google โค๏ธ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.