I am currently working on nodeJS to code APIs. I dont have much experience on coding, apologies if this might be a silly question. I tried to write a API for uploading files that can be named and its directory path is set dynamically. I could partially achieve objectives but facing little problems. I will show my code.
var express = require("express");
var multer = require('multer');
var app = express();
var crypto=require("crypto")
var mime=require("mime");
var path='./uploads'
var fs = require('fs');
var mkdirp = require('mkdirp');
var storage = multer.diskStorage({
destination: function (req, file, callback) {
callback(null, path);
console.log("Im in storage destination"+path);
},
filename: function (req, file, callback) {
console.log("Im in storage filename"+path);
//callback(null, file.fieldname + '-' + Date.now());
crypto.pseudoRandomBytes(16, function (err, raw) {
callback(null, Date.now() + '.' + mime.extension(file.mimetype));
});
}
});
var upload = multer({ storage : storage}).single('userPhoto');
app.post('/photo',function(req,res){
path += "/pics/shanmu/";
console.log("Im in post , outside upload"+path);
upload(req,res,function(err) {
console.log("Im in post , inside upload"+path);
if(err) {
return res.end("Error uploading file.");
}
res.end("File is uploaded"+path);
console.log("File is uploaded"+path);
});
});
app.listen(3000,function(){
console.log("Working on port 3000");
});
And this is my Folder structureWhen I run my code the file should get uploaded in uploads folder which you can see in the image and also has another folder inside and another (./uploads/pics/shanmu) when i try to trigger it form the postman I can do it only once, when i tries again i couldnt upload my files. Please help. Thanks in advance.
via shanmu sanjay
No comments:
Post a Comment