I am using nodejs multer to upload an image file to image uploads directory. After uploading, how can this particular image be displayed in html img tag in client browser. What is the url?
When I type in http://localhost:3000/uploads/1591342432.jpeg, it says cannot get the file.
var storage = multer.diskStorage({
destination: function (req, file, cb) {
cb(null, "./uploads/");
},
filename: function (req, file, cb) {
cb(null, Date.now() + ".jpeg");
},
});
const upload = multer({ storage: storage });
router.post("/upload", upload.single("file"), async (req, res) => {
try {
console.log("uploading...");
console.log(req.file.filename);
res.json({ cool: "yes" });
// res.json({ file: req.file });
} catch (error) {
console.log(error);
}
});
It seems you are using multer to upload img to a local folder called uploads.
I will recommend the following tutorial: upload img to firebase
This tutorial uses multer to upload the cloud firebase. Once you upload the image, you will get the link to the image where it is stored on the cloud and the same link you can use on the other server
I think I need to set a static directory:
app.use(express.static("uploads"));
Then I can access the image file as:
http://localhost:3000/1599134489853.jpeg
If you haven't already, you will need to set GET path for the image resource when attempting to fetch via http://localhost:3000/1599134489853.jpeg. For an express app, it appears the current simple/preferred method for returning the file is res.sendFile. Otherwise, you can generate stream and return as demonstrated here.
Related
I found a example from expressjs:
res.download('/report-12345.pdf');
to prompt the user for download. But i pass a url as parameter. It not working.
res.download just accepts path to filesystem in local.
For your requirement you can do one of below:
1) use res.redirect({URL})
2) get that file from URL and then send file to client like :
app.get('/', function(req, res){
http.get(URL, function(file) {
file.pipe(res);
});
});
This worked for me
const https = require("https");
const fileName = "the file name" + ".mp4";
https.get(url, function (file) {
res.set('Content-disposition', 'attachment; filename=' + encodeURI(fileName));
res.set('Content-Type', 'video/mp4');
file.pipe(res);
});
Here select the Content-Type for you file
Here's a list of mostly all content type
In the fileName add the file extension of your file i.e. ( .jpg , .png , .txt)
The first parameter to the res.download() method is the absolute path to the file on the filesystem, not a network URL. So if you say res.download('/report-12345.pdf'); you are trying to download the report-12345.pdf file from the root folder of your filesystem.
I got this third party lib which generates a screenshot.
I want to save this on my server. I'm using Axios.It's probably something with blobs, arraybuffers etc?
How do I send it?
Axios.post('/api/saveimage', { ??? })
Using NodeJs express on backend. How do I save this to a physical image file?
Well at the frontend you need to send it like this:
let formData = new FormData()
formData.append("image", file)
axios.post("/api/saveimage",formData)
At the first step you create a FormData, then you append the file. In this case i named the file image. Now lets go to the next step. You will need multer on your nodejs side.
npm i multer
The first think you need to do, is to create an middleware:
const multer = require("multer");
const whitelist = ["image/png", "image/jpeg", "image/jpg", "image/webp"];
const storeImages = multer.diskStorage({
destination: async function (req, file, cb) {
if (!whitelist.some((type) => type === file.mimetype)) {
return cb(new Error("File is not allowed"), "/");
}
cb(null, "your/destination/path");
},
filename(req, file, cb) {
let [name] = file.originalname.split(".");
cb(null, name + ".png");
},
});
exports.uploadImageStorage = multer({
storage: storeImages,
});
Here watch out: Your destination path should exist. Also dont forget an extension for your file in this case .png
Now you create your route:
const { uploadImageStorage } = require("../yourstorage")
app.post("/api/saveimage", uploadImageStorage.single("image"), (req, res) => {
let file = req.file
let path = file.path
})
Here you need to know at uploadImageStorage.single("image") i used image like i used it in formData.append("image", file) they need to be the same.
Now you can save the path of your file into a database. You can also transform your image with sharp if you want
From my experience if you have folder called static and you have a image inside of it like photo.png you usually get the photo with localhost:3000/photo.png and not with localhost:3000/static/photo.png
You will need to remove static from your path if you have this setup. Otherwise if you try to display the image on the frontend you wont see it.
I'm make api to upload files using node js.
i using multer for handle multipart/form-data
but when i console.log(req.file) it appears undefined
Route
const uploadController = require('../controller/upload.server.controller');
const multer = require('multer');
const upload = multer({ dest: 'uploads/' });
/**
* Routes
*/
module.exports = function (app) {
app
.route('/api/upload')
.post(upload.single('image'), uploadController.upload);
};
Controller
exports.upload = async function (req, res) {
console.log(req.file);
};
my request with postman
Try using req.file as per the docs source: multer
// init
const multer = require('multer');
const path = require('path');
// "images" are the folder name
const fileStorage = multer.diskStorage({
destination: (req, file, cb) => {
cb(null, 'images');
},
});
// put this to config the multer
app.use(multer({ storage: fileStorage }).single('image'));
// this is for serving file staticly with "path" module
app.use('/images', express.static(path.join(__dirname, 'images')));
Also make sure you write enctype=multipart/form-data in the form tag not in the input tag AND
add type=file attribute in the input tag
Try this:
app.post('/api/upload', upload.single('image'), function (req, res, next) {
console.log(req.file);
})
I have also encountered similar problem. Everytime I restart my server postman provided req.file gives undefined. I thought maybe I habe made a bug but I couldn't figure out what was wrong.
Then I tried creating a new request in postman and when I requested req.file works perfectly. I am trying to figure out what is wrong with Postman or am I making a mistake while sending a request.
I'm trying to use multer to upload a file. There is a boolean preservePath method, but the the API is vague on how to implement. I need to extract the original absolute file path from the file to be uploaded for use in a workflow pipeline on a closed network.
My understanding is that the optional methods are setup in the variable assignment.
Here is what I think is the relevant storage definition:
const storage = multer.diskStorage({
destination: './public/uploads/',
filename: function(req, file, cb){
cb(null,file.fieldname + '-' + Date.now() +
path.extname(file.originalname));
console.log(file);
}
});
const upload = multer({
//*********************************
preservePath: true,
//*********************************
storage: storage,
}).single('myImage');
Also, any guidance/input on how to construct clearer questions and clarifications would also be helpful.
I am now using Express4 and want to upload files to the file system of the server. (for example, save the files in the public/files folder.)
There are several questions about how to user formidable or busboy to parse the request like this example:
var formidable = require('formidable'),
http = require('http'),
util = require('util');
http.createServer(function(req, res) {
if (req.url == '/upload' && req.method.toLowerCase() == 'post') {
// parse a file upload
var form = new formidable.IncomingForm();
form.parse(req, function(err, fields, files) {
res.writeHead(200, {'content-type': 'text/plain'});
res.write('received upload:\n\n');
res.end(util.inspect({fields: fields, files: files}));
});
return;
}
// show a file upload form
res.writeHead(200, {'content-type': 'text/html'});
res.end(
'<form action="/upload" enctype="multipart/form-data" method="post">'+
'<input type="text" name="title"><br>'+
'<input type="file" name="upload" multiple="multiple"><br>'+
'<input type="submit" value="Upload">'+
'</form>'
);
}).listen(8080);
Such middleware could parse req to get the metadata, like the file path, name, size, etc. However, if I want to POST different files to different endpoints, I would like to use angularjs controller and service structure to process the uploading.
Wondering how can I get file path, name, etc to controller/service and post them to the backend. Then I can use the following codes to upload files.
api.post(url, function(req, res) {
var fs = require('fs');
//req.body.path: path of file, like, C:\\user\John\.....
//req.body.filename: name of file, like images.jpg
fs.readFile(req.body.path, function(err, data){
var uploadToPath = './public/files/' + req.body.filename;
fs.writeFile(uploadToPath, data, function(err){
if(err) {
res.send(err);
return;
}
});
});
});
I am also referring this solution, but it can only get the info like file size, but not the very important file path.
pls advise, many thanks.
For the node/express side:
Check out https://github.com/expressjs/multer
For the angular side:
Check out https://github.com/danialfarid/ng-file-upload
It makes uploading and saving single or multiple files super easy. They have an option in there for directory to automatically save to.
https://github.com/expressjs/multer#multeropts
File path will be your file path in express. So if its in a route the path will be that directory. Use a node core module path = require ('path') that will expose __dirname that'll let you change the path using core modules where needed. Path is relative to your system you won't get the clients path with the post request.
EDIT:
After reading the standard https://w3c.github.io/FileAPI/#attributes-blob
You can not get the file path. That's logical since that could be a potential privacy encroachment. If you're developing on node WebKit on the other hand your application would have access to users file system through the use of node core module path.