¡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!
Related
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 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
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
})
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
}
});
I'm new in Node.JS development. Recently I've struggling that problem: I want to upload photo to in "/uploads" directory in my project. I've added photo alone. But when its come to adding photo server and save its location path with photos owner id and description to Mysql DB I didn't make it. I know that Multer only accept multipart-form data.
Here is my Node.Js code
var models = require('../../models');
var express = require('express');
var router = express.Router();
var multer = require('multer');
var app = express();
var bodyParser = require('body-parser');
app.use(bodyParser.json({limit:'50mb'}));
app.use(bodyParser.urlencoded({extended:true, limit:'50mb'}));
const uuidv1 = require('uuid/v1');
var owner_id;
var description;
var storage = multer.diskStorage({
destination: function (req, file, cb) {
cb(null, 'uploads/')
},
filename: function (req, file, cb) {
const photo_id = uuidv1();
cb(null, photo_id + '.jpg');
addPhotoToDb(photo_id,owner_id,description);
}
});
function addPhotoToDb(photo_id,owner_id,description) {
models.PHOTOS.create({
photo_id: photo_id,
description: description,
owner_id: owner_id,
location_path: 'uploads/' + photo_id + '.jpg'
})
}
var upload = multer({ storage: storage }).single('photo');
router.post('/upload', function (req, res) {
//This part is problematic I tried so many things
//owner_id=req.files
//description=req.files
upload(req, res, function (err) {
if (err) {
}
res.json({
success: true,
message: 'Image uploaded!'
});
})
});
module.exports = router;
Also in Postman I'm sending request like that:
https://i.stack.imgur.com/04Qz1.png
In your screenshot you show the "body" tab. In the left there is the "headers" tab. Click on it and check that you have the content-type set to "multipart/form-data" because multer won't process any data that aren't on this content type.