I am new to node.js .And need to upload an image when an api is called,the image is given as multipart form data.
How could i get the image details as the response?
You can use multer.js as the body-parser. Its built on top of busboy.
Its quite well-documented .
The answer of this question is as follow :
fileupload.js :
var express = require("express"),
app = express();
// tell express to use the bodyParser middleware
// and set upload directory
app.use(express.bodyParser({ keepExtensions: true, uploadDir: "uploads" }));
app.engine('jade', require('jade').__express);
app.post("/upload", function (request, response) {
// request.files will contain the uploaded file(s),
// keyed by the input name (in this case, "file")
// show the uploaded file name
console.log("file name", request.files.file.name);
console.log("file path", request.files.file.path);
response.end("upload complete");
});
// render file upload form
app.get("/", function (request, response) {
response.render("upload_form.jade");
});
app.listen(3000);
View :
doctype 5
html
head
title Upload Form
body
h1 Upload File
form(method="POST", action="/upload", enctype="multipart/form-data")
input(type="file", name="file")
input(type="submit")
Related
I am using gridfs and mongoDB to store images in chunks. And whenever a user requests my server just sends a streamlined image file in response by piping.
Currently my code looks like this :
const download = async (req, res)=>{
try{
const fileName = req.params.name
await mongoClient.connect();
const database = mongoClient.db(dbConfig.database)
const bucket = new GridFsBucket(database, { // required for important methods like openDownloadStream
bucketName:dbConfig.imgBucket
})
const downloadStream = bucket.openDownloadStreamByName(fileName);
downloadStream.pipe(res) // it only displays an jpg/png image
// res.render("image") , I want to render this ejs page with a image in it and with some static content in it. I want to stream image
} catch(err){
res.status(501).render("error",{error: err})
}}
My output looks like :
my code output
It only renders a jpg file, like how above link is working see it.
but rather what i want to do is to get image from response object and render it with my other html elements.
Looks like you're trying to do too much at once.
You need to de-couple the desired streaming image from the initial rendering of your template. Include an image tag in your tempalte with a distinct api from which the image will stream, and the result will look something like your example.
Say your image is called test.png, your server index.js, and your ejs teplate index.ejs. The template (for the sake of your question) can be very simple: index.ejs-->
<h1> stream that image below! </h1>
<image src="/image" hieght="200px" width="200px";/>
Notice the src of this image - this will hit a distinct api on your backend that will stream the image.
The server index.js will look like this -->
var exp = require("express");
var fs = require("fs");
var app = exp();
app.set("view engine", "ejs");
app.get("/image", (req, res) => {
const streamReadFile = fs.createReadStream("test.png");
streamReadFile.pipe(res);
});
app.get("/", (req, res) => {
res.render("index");
});
app.listen(8080, () => {
console.log("listening on *:8080");
});
Notice here at the home route you render the template as
app.get("/", (req, res) => {
res.render("index");
});
The src in the image of your template then makes a request back to the server, hitting the /image route which will stream the desired image to your html
app.get("/image", (req, res) => {
const streamReadFile = fs.createReadStream("test.png");
streamReadFile.pipe(res);
});
Here's a working demo of the example above, where your image is streamed to an ejs template.
I'm trying to store an uploaded file,the file reached the server successfully but don't know how to store it using the multiparty library that's the code:
var multipart = require('connect-multiparty');
var multipartMiddleware = multipart();
app.post('/upload_audio', multipartMiddleware, function(req, resp) {
console.log(req.body, req.files);
if(req.files){
resp.status(200).send("Uploaded!!!");
}
});
By default the 'connect-multipart' module save the file in a default file which is
"C://Users//ur-username//AppData//Local//Temp" but you can change it by adding this line :
app.use(multipart({ uploadDir: "ur_path"}));
I am wanting to post an image in the form of binary to my Express app.
I'm assuming it should come through in the req.body object but will need some form of middleware to be able to handle binary data?
When I send an image as binary from postman and try log req.body, the object is empty.
I am using express-generator as a boilder plate which comes with body-parser like so:
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
I had a look at Multer but think that is just for multipart data
Also looked at busboy but couldn't figure out if that will handle binary data.
Am I correct that the post data will still come through in req.body?
And what middleware do I need to handle binary data?
Thanks
The method I ended up using:
const multer = require('multer')
const storage = multer.memoryStorage()
const upload = multer({ storage: storage })
router.post('/upload', upload.single('image'), function(req, res, next) {
const image = req.file.buffer
});
Unfortunately, you can't use the body-parser to handle the binary data like files and stuff like that. But wut you can do is use a module call formidable to handle this
Example snipper
app.post('/', (req, res) => {
const form = new formidable.IncomingForm();
form.parse(req, (error, fields, files) => {
if(error){
console.log(error)
}
console.log(fields.name)
const cuteCat = files.cat_image;
console.log(cuteCat.name) // The origin file name
console.log(cuteCat.path) // The temporary file name something like /tmp/<random string>
})
});
<input name="cat_image" type="file" />
<input name="name" type="text" />
I am able to upload images using Node.Js and Multer. The images are saving in encrypted format with random names. How can I retrieve and display images in a .jade file or .hetml file?
//My Code to upload image
router.post("/upload", function(req, res, next){
if (req.files) {
console.log(util.inspect(req.files));
if (req.files.myFile.size === 0) {
return next(new Error("Hey, first would you select a file?"));
}
fs.exists(req.files.myFile.path, function(exists) {
if(exists) {
res.end("Got your file!");
} else {
res.end("Well, there is no magic for those who don’t believe in it!");
}
});
}
});
// Upload page (Jade file)
form#fileUpload(method="post" action="/uploads/upload" enctype="multipart/form-data")
label(for="payload") Select a file to upload:
input#fileToUpload(type='file', name='myFile')
//input#payload(type="file" name="myFile" accept="image/*")
br
button#upload Upload
var multer = require('multer'),
upload = multer({dest: 'uploads/'});
app.post('/multipart-upload', upload.single('file'), function(req, res){
var filename = req.file.path;
console.log('Uploading File: ' + JSON.stringify(req.file));
});
Multer needs a path to upload the file. You can keep the path inside the public/static folder of express, and directly link the file.
Or You can use the static files middleware to serve the files in the upload folder and directly link them.
app.use('/image-uploads', express.static('uploads'));
Problem
I have a server that needs to upload files, I have tried multiparty, connect-multiparty and multer.
But every case, has the same problem: the file only uploads some times, i mean, i could send a file and there is a chance that the libraries don't parse the files, and never continue the code, resulting on not uploading the files.
In a While, the request send an error "Request Aborted", but its the normal response when the request time out
This is the problematic node.js file:
var multiparty = require('multiparty');
var multer = require('multer');
var upload = multer({
dest: "/uploads/"
});
///----rest of code----
//1. Multiparty
app.post("/upload",[function(req, res){
var form = new multiparty.Form({uploadDir:'/uploads/'});
console.log("to upload")
form.parse(req, function (err, fields, files) {
console.log("uploaded");
res.json({uploaded: true});
})
}]
//2. multer
app.post("/upload2",[
function(req, res, next){
console.log("to upload");
next();
},
upload.fields([
{name: "file"},
{name: "thumbnail"}
]),
function(req, res){
console.log("uploaded");
res.json({uploaded: true});
}]
Make sure your form looks like this
<form enctype="multipart/form-data" action="..." method="...">
...
</form>
And to be honest you will be better off using node-formidable. It is the most used multipart/form-data package on npm.
The example works straight out of the box.
Cheers
https://stackoverflow.com/a/23975955/4920678
I was using the setup from this answer, to use http and https over the same Port.
Turns out, the setup with that proxy damaged the packages that where too large or something, and then the files never get parsed