I'm using express-fileupload module to parse uploaded file.
Upload is done with axios.
const formData = new FormData();
formData.append("file", data.gameCover);
formData.append("gameTitle", data.gameTitle);
formData.append("gamePrice", data.gamePrice);
formData.append("description", data.description);
return axios.post(apiUrl + "/games/add", formData).then(res => {
dispatch({ type: ADD_GAME, payload: res.data.game });
});
This is the POST request
Serverside code looks like this:
router.use(fileUpload());
router.post("/add", (req, res) => {
if (!req.files) return res.status(400).send("No files were uploaded.");
Of course I'm getting "No files were uploaded" when trying to upload.
Finally after debugging step after step found that data.gameCover is an array
so that's the solution
formData.append("file", data.gameCover[0]);
You can optionaly use multer for handling multipart/formdata.
you can then get the uploaded file as follows
const express = require('express');
const path = require('path');
const router = express.Router();
const multer = require('multer');
const storage = multer.diskStorage(
{destination: (req, file, cb)=>{
cb(null, path.join(__dirname, '../uploads'));
},
filename: (req, file, cb)=>{
cb(null, file.originalname);
}
});
let upload = multer({storage: storage});
// access the uploaded file with your route handler
router.post('/upload',upload.single('file'), (req, res, next)=> {
if(req.file){
//you can access your uploaded file
}
});
Related
¡Hello world!
I'm making a upload xls functionality. So, I use multer module in order to archieve this. Nevertheless, when I tested in Postman return me errors:
Upload.js(controlller):
const multer = require('multer');
const express = require('express');
module.exports = {
upload(req, res){
multer.diskstorage({
destination: function(req, file, cb){
cb(null, _dirname + '/uploads')
},
filename: function(req, file, cb) {
cb(null, Date.now() + '-' + '.xlsx')
}
}).then(res => res.status(200).json({
message: "File upload succesfully",
})
).catch(error => res.status(401).send(error))
}
And there is the routes:
const express = require("express");
const router = express.Router();
const { func } = require('#hapi/joi');
const controller = require('../../v1/controllers/Upload');
module.exports = (router) => {
router.route('upload').post(controller.upload);
return router;
}
And this sreenshot correspond Postman test
Really, what I'm tryng to make is a Upload functionality that upload and import xls files. With no database involved. But I dont know what I'm doing wrong. So if anyone could help or give me some tips in order to fullfill this goal, I'd be really grateful for this help
Thanks!
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");
})
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
i want to read the csv data uploaded to backened.
for this i am sending the data via post from front end..
frontend code:
fileEvent(e) {
this.filedata = e.target.files;
if (this.filedata.length > 0) {
const file: File = this.filedata[0];
console.log(file);
const formData: FormData = new FormData();
formData.append('files', file, file.name);
this.http.post('myUrl', {file: formData}, this.options)
.subscribe((res) => {
});
}
}
screenshot of my file:
now on backened i have written route on api.js that directs me
to the controller i have created.
my api.js code:
router.post('/product/csvdata', function (req, res) {
productimport.importcsvProduct(req, res);
});
and finally on my controller i am consoling my data:
var product = {
importcsvProduct: function (req,res) {
console.log(req.body.file);
}
};
module.exports = product;
but i am getting empty {} in console..??
can anyone check whats wrong with this..??
You need to use a file handling middleware in this case, such as multer.
const express = require('express')
const multer = require('multer')
const upload = multer({ dest: 'uploads/' })
const app = express()
app.post('/profile', upload.single('csvdata'), function (req, res, next) {
// req.file is the `csvdata` file
// req.body will hold the text fields, if there were any
})
So on first server I have route like this:
const express = require('express');
const router = express.Router();
const FormData = require('form-data');
const fetch = require('node-fetch');
const multer = require('multer');
const storage = multer.memoryStorage();
const upload = multer({ storage });
router.post('/', upload.single('file'), async (req, res) => {
const form = new FormData();
form.append('folderId', req.body.folderId);
form.append('file', req.file.buffer, req.file.filename);
const result = await fetch('http://localhost:3003/users', { method: 'POST', body: form }).then(res => res.json());
res.json(result);
})
On this server, it works fine, I can see req.file and it's buffer. So I wanna send this file (without storing it on first server, it exists only in memory and as buffer) to another.
Other server route is like this:
const express = require('express');
const router = express.Router();
const multer = require('multer');
const path = require('path');
const putanja = path.join(__dirname, '../uploads/users');
const storage = multer.diskStorage({
destination: (req, file, cb) => {
console.log('entered here?')
if (!req.body.folderId) return cb({ message: 'no folderId' });
if (!fs.existsSync(putanja + '/' + folderId)) fs.mkdirSync(putanja + '/' + folderId);
cb(null, putanja + '/' + folderId);
},
filename: (req, file, cb) => cb(null, file.originalname)
});
const upload = multer({ storage });
const fs = require('fs');
router.post('/', upload.single('file'), async (req, res) => {
console.log(req.body)
console.log(req.file)
res.json({ status: 'ok' })
})
So on second server, it doesn't even enter the multer middleware, req.file is always defined, and that console.log('entered here?') is never seen. Looks like I'm not passing data as multipart-form?
Also, second server, when sending file directly to it via postman, works.
So my question, how do I send that file? As a buffer? Stream? Base64? I think I tried everything, even changed node-fetch to request, but still no luck.
So on second server, it doesn't even enter the multer middleware, req.file is always defined, and that console.log('entered here?') is never seen. Looks like I'm not passing data as multipart-form?
So this mean your second server doesn't understand the Content-Type of request.
So do one thing add Content-Type parameter in header when you are sending request to second server
Add Content-Type to multipart/form-data
or if you don't know pass headers : {
'Content-Type' : undefined
} http will set header for you
You send your request to /users (http://localhost:3003/users) yet your second server expects the request on /.
Try changing either one to match the other.
'use strict';
const express = require('express');
const multer= require('multer');
const concat = require('concat-stream');
const request = require('request');
const router = express.Router();
function HttpRelay (opts) {}
HttpRelay.prototype._handleFile = function _handleFile (req, file, cb) {
console.log('hell0 proto');
file.stream.pipe(concat({ encoding: 'buffer' }, function (data) {
const r = request.post('/Endpoint you want to upload file', function (err, resp, body) {
if (err) return cb(err);
req.relayresponse=body;
cb(null, {});
});
const form = r.form();
form.append('uploaded_file', data, {
filename: file.originalname,
contentType: file.mimetype
});
}))
};
HttpRelay.prototype._removeFile = function _removeFile (req, file, cb) {
console.log('hello');
cb(null);
};
const relayUpload = multer({ storage: new HttpRelay() }).any();
router.post('/uploadMsgFile', function(req, res) {
relayUpload(req, res, function(err) {
res.send(req.relayresponse);
});
});
module.exports = router;