how to upload file on server in node js? - javascript

could you please tell me how to upload the file on some directory current example (uploads folder) .Here is my server side code
app.post('/upload', function (req, res) {
console.log('abcc')
upload(req, res, function (err) {
if (err) {
res.json({error_code: 1, err_desc: err});
return;
}
res.json({error_code: 0, err_desc: null});
});
});
full code node js
https://repl.it/repls/LustrousCharmingCommunication
I used this server and hit the service using client and upload only attached file
here is my request client code
https://jsbin.com/luwezirive/edit?html,js,output
$(function () {
$('.submit').on('click', function (e) {
e.preventDefault();
e.stopPropagation();
if ($('#fileId').val().length === 0) {
alert('please insert file')
} else {
var form = $('#fileUploadForm')[0];
// Create an FormData object
var data = new FormData(form);
console.log('fffff')
$.ajax({
url: 'https://lustrouscharmingcommunication--five-nine.repl.co/upload',
type: 'POST',
data: data,
cache: false,
enctype: 'multipart/form-data',
dataType: 'json',
processData: false, // Don't process the files
contentType: false, // Set content type to false as jQuery will tell the server its a query string request
success: function (data, textStatus, jqXHR) {
console.log('succsss');
if (typeof data.error === 'undefined') {
// Success so call function to process the form
}
else {
// Handle errors here
console.log('ERRORS: ' + data.error);
}
},
error: function (jqXHR, textStatus, errorThrown) {
// Handle errors here
console.log('ERRORS: ' + textStatus);
// STOP LOADING SPINNER
}
});
}
})
})
I am getting success but file is not uploaded why ?
upload method
var storage = multer.diskStorage({ //multers disk storage settings
destination: function (req, file, cb) {
cb(null, './uploads/')
},
filename: function (req, file, cb) {
var datetimestamp = Date.now();
cb(null, file.fieldname + '-' + datetimestamp + '.' + file.originalname.split('.')[file.originalname.split('.').length - 1])
}
});
var upload = multer({ //multer settings
storage: storage
}).single('file');
any update ?

The simplest way is using multer. https://github.com/expressjs/multer
Example taken from the documentation:
var express = require('express')
var multer = require('multer')
var upload = multer({ dest: 'uploads/' })
var app = express()
app.post('/profile', upload.single('avatar'), function (req, res, next) {
// req.file is the `avatar` file
// req.body will hold the text fields, if there were any
})

Related

Problem uploading image to local folder with node and Multer

I'm struggling uploading an image to a local folder using Node and Multer.
The response i get it's successfully, but the image don't save in the folder.
I have already lost a week trying to fix it
And yes, i have checked the destination route, in case you wonder.
This is my frontend:
<form id="tasasImage" enctype="multipart/form-data" style="display: flex; flex-direction: column;">
<input type="file" name="photo" id="photo" class="file"> <br>
<div id="uploadImg" class="btn btn-primary">ENVIAR</div>
</form>
<script>
$("#uploadImg").click(function () {
if ($('#photo').val().length > 0) {
var formData = new FormData($('#tasasImage')[0]);
console.log([...formData])
$.ajax({
url: "",
data: formData,
type: "POST",
processData: false,
contentType: false,
success: function(r){
console.log('Uploaded successfully');
$("#photo").val('');
},
error: function (e) {
console.log("some error", e);
}
});
}
</script>
And the backend:
var storageTasas = multer.diskStorage({
destination: function(req, file, callback) {
callback(null, config.urlBase+'public/images/tasas');
},
filename: function(req, file, callback) {
var name = now+'-'+file.originalname;
callback(null, name);
}
})
var uploadTasas = multer({ storage: storageTasas }).single('photo');
const tasasUploadImage = (req, res) => {
uploadTasas(req, res, (err) => {
if (err) { console.error(err); }
else {console.log('Ssuccessfully Uploaded') };
})
res.send({'file': now});
}
router.post('/admin/aliados/tasas/:id', adminController.tasasUploadImage);
The url you are passing empty in the JQuery / Client script, it should be url : /admin/aliados/tasas/1234
The form data should be like this
var formData = new FormData($('#tasasImage'));
simple multipart file upload with express.js and multer with ajax

why request body is blank in node js + react?

I am sending post request with FormData .but when I checked on node server my body is blanked why ?
I do the following steps
let formData = new FormData();
// add one or more of your files in FormData
// again, the original file is located at the `originFileObj` key
formData.append("file", values['Temp_id_card'].fileList[0].originFileObj);
formData.append("Emp No",values['Emp No'].toLowerCase())
formData.append("Remarks",values['Remarks'])
formData.append("UpdatedStatus",values['Status'])
formData.append("id",id)
formData.append("Att Date",attDate)
send data like that
export const sendPostRequest1 = (url, data, config = {}) => {
let updatedConfig = {
headers: {Authorization: `Bearer ${getAuthToken()}` || ""},
...config
};
return axios.post(url, data, updatedConfig);
}
when i checked on network tap it shows data is send
but When debug on node server it shows empty body why ?
Node js code
var Storage = multer.diskStorage({
destination: function(req, file, callback) {
if(req.user.userId === req.body.userId){
callback(null, "./Images");
}else {
throw new AuthenticationError("Unauthorized User");
}
},
filename: function(req, file, callback) {
callback(null, file.fieldname + "_" + Date.now() + "_" + file.originalname);
}
});
var upload = multer({
storage: Storage
}).array("file", 1); //Field name and max count
router.post('/upload', (req, res) => {
upload(req, res, function(err) {
if (err) {
return res.end("Something went wrong!");
}
return res.end("File uploaded successfully!.");
});
});
when I checked on this if(req.user.userId === req.body.userId){ line req.body is empty object ?
I also added this my middleware
app.use(bodyParser.json({ limit: "100mb"}));
app.use(bodyParser.urlencoded({ limit: "50mb",extended: false }));
app.use(requestLogger);
app.use(helmet());
Fetched the same issue(Angular+NodeJs), and solved by the help of middleware.
Just write
router.post('/upload', upload.single('file'), (req, res, next) => {
instead of
router.post('/upload', (req, res) => {
For more details

how to upload image to mongodb using node js and express

I'm making a web app that allows users to upload and search for a recipe. A user can upload a recipe by filling a form and press a button to perform a POST request. I managed to save the recipe object, but I can't assign an image to it. I tried to use Multer, but I get "underfined" when I do log(req.file). I followed YouTube tutorials which only had app.js and index.ejs and it works, so I don't know if it's my Ajax code causing the issue??!!.
I have main.handlebars and main.css, and I have a folder called uploads but still always get undefined in the terminal, below is part of my code:
THANKS!!
upload.handlebars:
<label for="Userphrase">Recipe Name:</label>
<input type = "text" name = "recipeName" id = "recipeName"><br>
<label>Upload an image:</label>
<div class="container">
<input name="myImage" type="file"<br>
</div>
.
.
.
<script type = "text/javascript" src = "/public/palindrome.js"></script>
Ajax, only the request is here since i do error checking before that:
$("form").submit(function(e){
$.ajax({
type: "POST",
url: "/upload",
data: obj,
success: function(data){
alert("recipe added successfully!");
},
dataType: "json"
});
}
index.js:
at the top i have:
const storage = multer.diskStorage({
destination: './public/uploads/',
filename: function(req, file, cb){
cb(null, file.fieldname + '-' + Date.now() + path.extname(file.originalname));
}
});
const upload = multer ({
storage: storage
}).single('myImage');
then inside the POST route i have:
router.post('/upload',(req,res)=>{
upload(req, res, (err) => {
if(err){
res.render('index',{
msg: err
});
}else{
console.log(req.file);
res.send('test');
}
});
You have to send image in form data like
var formData = new FormData();
formData.append('imageName', imageFile);
on node side user same name('imageName') for multer it will get image from it
for more to multer check
https://www.npmjs.com/package/multer
For simplicity's sake, just use HTML form with enctype set to multipart/form-data on the client side. On the server side, say you're using Node.js, the uploaded files can be found in the request provided you're using the multer middleware to parse the form data. That's it.
You need to append that file to formData and then send it to server
Javascript:
var formData = new FormData();
jQuery.each(jQuery('#fileUpload')[0].files, function (i, file) {
formData.append('file', file);
});
$.ajax({
type: 'POST',
url: //To your route eg: /saveImage,
data: formData,
contentType: false,
processData: false,
success: function (result) {
if (result.status != 0) {
console.log(result.message)
return;
}
console.log(result.message)
}
});
Now at your route use multer
Node
var multer = require('multer')
var path = require("path");
// Check for extension of image
const getExtension = file =>{
if (file.mimetype == "image/jpeg")
ext = ".jpeg"
else
ext =".png"
return ext;
}
//initialize multer
var storage = multer.diskStorage({
destination: function (req, file, cb) {
cb(null, path.join(__dirname, '../public/images'))
},
filename: function (req, file, cb) {
cb(null, file.fieldname + '-' + Date.now() + getExtension(file))
}
})
var upload = multer({storage:storage})
router.post('/saveImage', upload.single('file'), (req, res, next)=>{
if (req.file && req.file.mimetype != 'image/jpeg' && req.file.mimetype != 'image/png')
return res.json({
status:1,
message:"Please Choose JPG or PNG images"
})
if(req.file){
let iamge = "/images/" + req.file.filename
res.json({
status:0,
message:"Successfully saved",
path : image
})
}
})

ajax not able to capture response from Node Express in multer

I am using multer to upload image and it works great, I am able to see the data getting printed to console, but I am not sure how to capture this data and manipulate it in browser. Below is my code:
var multer = require("multer");
var storage = multer.diskStorage({
destination: function(req, file, callback){
callback(null, 'uploads'); // set the destination
},
filename: function(req, file, callback){
callback(null, 'FILE1' + '.jpg'); // set the file name and extension
}
});
var upload = multer({storage: storage});
app.post('/', upload.any(), function(req, res, next) {
console.log(req.files);
var image = req.files;
console.log(image);
res.send(image); //this should come to jquery response object in browser, but not sure why it is not
});
and below is my jquery code that should be able to get above data in response object:
$('body').on('click', '#uploadFile', function (event) {
$.ajax({
type: 'POST',
url: '/',
success: function (response) { //this is always "" not sure why, I am expecting multer response to be here
console.log('successfully uploaded', response);
},
error: function () {
console.log('coudn\'t upload');
}
});
//return false;
})
I think the problem is that by the time I capture response in jquery, multer hasnt uploaded the file so I have no or blank response in ajax. I am not sure how to fix this.
app.post('/', upload.any(), function(req, res, next) {
console.log(req.files);
var image = req.files;
console.log(image);
res.send(image); // this should come to jQuery response object
res.end(); // !!! - note this!
});
You have to add res.end() to finalize the response.

got uploading twice when creating a new name with adding name from textbox and original file name using multer and angularjs

so, I just want to create name with adding name from textbox to the original file
script.js
angular.module('signin').service('fileUpload', ['$http', function ($http)
{
this.uploadFileToUrl = function(file, uploadUrl, name){
var fd = new FormData();
fd.append('file', file);
fd.append('name', name);
$http.post(uploadUrl, fd, {
transformRequest: angular.identity,
headers: {'Content-Type': undefined}
})
.success(function(){
console.log("uploaded");
})
.error(function(){
console.log("fail to upload");
});
}}]);
fileUpload.uploadFileToUrl(file, uploadUrl, $scope.id);
and in the app.js
var storage = multer.diskStorage({
destination: './upload/',
filename: function (req, file, cb) {
cb(null, name + "_"+file.originalname)
}
})
var upload = multer({ storage: storage });
app.post('/move', upload.single('file'), function(req,res,next){
name = req.body.name;
console.log('Uploade Successful ', req.file, req.body);
});
and the problem is the output from 'name' variable is always undefine in first time but around 2 second - 1 minutes, console update the log and show that the multer do an uploading file again with the 'name' variable has a value from the input . because of that, it's creating the unneeded file (it save the file twice, one is the unexpected file(the file with 'undefiene'in front of original name) and the file that I need), so how to fix this problem?
I got the same problem because of my configuration issues, Please check your configurations again, from my working code segment,
// create storage
var location_hotels = multer({ dest: './uploads/images' });
var cpUpload = location_hotels.fields([{ name: 'title', maxCount: 1 },
{ name: 'text', maxCount: 1 }, { name: 'myfile', maxCount: 8 }]);
router.post('/upload_test', cpUpload, function (req, res, next) {
console.log(req.files); // return if files exist
console.log(req.files); // return if field exist
});
// upload data as form data, my angular service is,
angular.module('testServices', [])
.service('MyService', function($http) {
this.uploadFileToUrl = function(file, title, text, uploadUrl){
var payload = new FormData();
payload.append("title", title);
payload.append('text', text);
for(var x = 0; x<file.length; x++) {
payload.append('myfile', file[x]);
}
console.log(payload);
return $http({
url: uploadUrl,
method: 'POST',
data: payload,
//assign content-type as undefined, the browser
//will assign the correct boundary for us
headers: { 'Content-Type': undefined},
//prevents serializing payload. don't do it.
transformRequest: angular.identity
});
}
});
i guest it may help you.
// Or please change your code as below and try,
router.post('/upload', function(req, res) { // get your post request
profilePictures(req, res, function(err) { // do multer tasks
if (err) {}
}
});
});

Categories

Resources