multer, npm - originalname is garbled:( - node.js

I'm creating a video upload API in Node.js. To upload it, I have to handle the multipart request, so I'm using npm library "multer".
Try to send a video file(like below) in Postman.
テスト_test.mp4
"テスト" is some Japanese character. And when posting that, the result is:
console.log(req.file.originalname)
=> ƹ�(_test.mp4
I want
originalname=>テスト_test.mp4
not
originalname=>ƹ�(_test.mp4
Implementation:
const express = require('express')
const router = express.Router()
const request = require('request')
const multer = require('multer')
var storage = multer.diskStorage({
destination: function (req, file, cb) {
cb(null, "some/dest/dir")
}
})
var upload = multer({
storage: storage
}).single("file")
router.use(upload)
router.post("/videos", functinon(req, res, next){
console.log(req.file.originalname)
})
Postman:
・request header Content-Type: multipart/form-data
・request body file:テスト_test.mp4
Does anybody have ideas?

Related

How to disable restify.plugin.bodyParser for file uploads

This question is very similar to How to disable Express BodyParser for file uploads (Node.js). But the answer they have provided is for Express and I have tried the solution with the Restify 7, and it does not seem to work.
I'm using Node.js + Restify to build Restfull application. I am using BodyParser,to parse post parameters. However, I would like to have access to multipart form-data POSTS.
I use multer, multer-s3 and aws-sdk and I want to have access to the data to send them to digitalocean sapce. But all file uploads are parsed automatically by restify.plugin.bodyParser.
Is there a way for me to disable the BodyParser for multipart formdata posts without disabling it for everything else?
This is an example code :
const restify = require('restify');
const errors = require('restify-errors');
const aws = require('aws-sdk');
const multer = require('multer');
const multerS3 = require('multer-s3');
const server = restify.createServer();
server.use(restify.plugins.acceptParser(server.acceptable));
server.use(restify.plugins.bodyParser());
// Set S3 endpoint to DigitalOcean Spaces
const spacesEndpoint = new aws.Endpoint('nyc3.digitaloceanspaces.com');
const s3 = new aws.S3({
endpoint: spacesEndpoint
});
const upload = multer({
storage: multerS3({
s3: s3,
bucket: 'space_name',
acl: 'public-read',
key: function (request, file, cb) {
console.log(file);
cb(null,new Date().toISOString());
}
})
}).single('logo');
server.post('/upload', async (req, res, next) => {
upload(req, res, async (error) => {
if (error) {
console.log(error);
return next(new errors.InvalidContentError(error));
}
console.log('File uploaded successfully.');
res.send(200);
next();
});
});
I just changed server.use(restify.plugins.bodyParser()); by server.use(restify.plugins.jsonBodyParser()); and everything is working fine

Upload a image with other key-value parameters to postman in NodeJS/Express

I'm new to NodeJS and I tried this to post images through postman.
But I can't figure out where am I lacking?
The postman parameters :
NodeJS Code
Now to access these values in my NodeJS, I'm currently doing this :
var express = require('express');
var bodyParser = require('body-parser');
const router = express.Router();
router.use(bodyParser.json());
router.post('/postData/uploadStory', function(req, res) {
console.log(req.files);
console.log(req.body);
res.json("Hi");
})
How can I get access to the image and the key-value?
Also looked at express-fileupload node-module for doing this work for me.
Created a simple ejs with input name=foo type=file
tried to access it in the server.js file as console.log(req.files).
Didn't work.
Am I missing something? Please help. Thanks.
multer is best option to upload file in node.js
create separate folder for multer like multerHelper.js
const multer = require('multer');
let fs = require('fs-extra');
let storage = multer.diskStorage({
destination: function (req, file, cb) {
fs.mkdirsSync(__dirname + '/uploads/images'); // fs.mkdirsSync will create folders if it does not exist
cb(null, __dirname + '/uploads/images');
},
filename: function (req, file, cb) {
console.log(file);
cb(null, Date.now() + '-' + file.originalname);
}
})
let upload = multer({ storage: storage });
let createUserImage = upload.single('photo');
let multerHelper = {
createUserImage,
}
module.exports = multerHelper;
In your routes import multerhelper file
const multerHelper = require("../helpers/multer_helper");
router.post('/upload/:userid',multerHelper, function(req, res) {
console.log(req.files);
console.log(req.body);
res.json("Hi");
})

After upload an image using (nodejs & multer) the response is sent (to angular) but the image isn't moved to the destination folder

I'm a beginner in nodejs and angular, I'm trying to upload image using multer and image is uploaded successfully and send response but i can't find the image in the destination folder no moving happens.
I tried those paths for the folder: ./images
../../images but non of them work here is my hierarchy
project hierarchy
var express = require('express');
const router = express.Router();
var multer = require('multer');
var upload = multer({ storage: storage });
// SET STORAGE
var storage = multer.diskStorage({
destination: (req, file, cb) => {
cb(null, "./images")
},
filename: (req, file, cb) => {
cb(null, file.originalname.toLowerCase())
}
})
router.post('/', upload.single('image'), (req, res, next) => {
const file = req.file
if (!file) {
const error = new Error('Please upload a file')
error.httpStatusCode = 400
return next(error)
}
res.send(file);
})
module.exports = router;
I expected to find the uploaded image in the destination folder but the image isn't moved to it

How to upload a file in node.js server using multer

I'm trying to pass a file from my Angular app to a node.js server.
When I run the app, I get the following error:
Error: Please choose files
HTML:
<upload name="fileUpload" formControlName="fileUpload" #fileUpload (listChange)="updateList($event)" data-kind="primary"
[imagePreview]="true">
</upload>
Here is my updateList() method:
updateList(list: any) {
this.demolist = Array.apply(this, list);
this.attachmentReady.emit(this.demolist);
}
Node:
const express = require('express')
const app = express()
const bodyParser = require('body-parser')
const multer = require('multer');
let nodemailer = require('nodemailer');
let aws = require('aws-sdk');
const fs = require('fs');
var storage = multer.diskStorage({
destination: function (req, file, cb) {
cb(null, 'uploads')
},
filename: function (req, file, cb) {
cb(null, file.fieldname + '-' + Date.now() + path.extname(file.originalname))
}
});
var upload = multer({ storage: storage });
app.post('/postData', upload.array('fileUpload', 12), (req, res, next) => {
console.log(req.body);
res.json(req.body);
const files = req.files
if (!files) {
const error = new Error('Please choose files')
error.httpStatusCode = 400
return next(error)
}
res.send(files);
}
In a different project, multer is working as expected. Below is the HTML from that project:
<form action="/uploadmultiple" enctype="multipart/form-data" method="POST">
Select images: <input type="file" name="myFiles" multiple>
<input type="submit" value="Upload your files" />
</form>
The difference between my working code & the code that isn't working is that I'm able to use a standard input control if the type is file.
But I need to use an upload control now & my code isn't working when I make that one change.
Can someone please tell me how I can use this control to pass the file? Thanks a lot in advance!
After you have installed multer using npm install --save multer
Basic usage example:
var express = require('express')
var multer = require('multer')
var upload = multer({ dest: 'uploads/' })
var app = express()
app.post('/uploadmultiple', upload.single('myFiles'), function (req, res, next) {
// req.file is the `myFiles ` file
// req.body will hold the text fields, if there were any
})
app.post('/uploadmultiple', upload.array('myFiles', 12), function (req, res, next) {
// req.files is array of `photos` files
// req.body will contain the text fields, if there were any
})
For more information you can read documentation here

Configuring multer to upload files to nodejs server

The express Router is setup as such:
var router = require('express').Router();
var multer = require('multer');
var uploading = multer({
dest: './uploads/',
limits: {fileSize: 1000000, files:1},
});
router.post('/upload', uploading.single('avatar'), function(req, res) {
console.log('success');
});
module.exports = router;
I am attempting to upload files:
curl -F "image=#/Users/runtimeZero/Desktop/nassau.jpg" localhost:3000/auth/upload
The express server throws the below error:
Error: Unexpected field
at makeError (/Users/.../node_modules/multer/lib/make-error.js:12:13)
at wrappedFileFilter (/Users/../node_modules/multer/index.js:39:19)
...
...
at HeaderParser.push (/Users/.../node_modules/multer/node_modules/busboy/node_modules/dicer/lib/HeaderParser.js:46:19)
at Dicer._oninfo (/Users/.../node_modules/multer/node_modules/busboy/node_modules/dicer/lib/Dicer.js:197:25)
From multer documents this seems pretty straight forward. However, not so much when actually using it. What am i missing ?
If you look at the multer readme you will see that multer() returns an object that contains various functions that return different middleware, depending on your needs.
For example, to accept a single file whose name is 'avatar':
var upload = multer({dest: './uploads/'});
router.post('/upload', upload.single('avatar'), function(req, res) {
console.log('success');
});

Resources