javascript - How to upload,save and display file with node and express -
i new in nodejs , trying make form node , express can upload save , display image or file. have app.post information works.
i trying did not work. think missing dont know tried many answers nothing worked me. hope can me.
thanks in advanced.
there code
var express = require('express'); var bodyparser = require('body-parser'); var fs = require('fs'); var busboy = require('busboy'); var path = require('path'); var app = express(); app.use(bodyparser()); app.get('/information', function(req,res) { var html = '<form action="/information" method="post">' + 'enter name:' + '<input type="text" name="username" placeholder="..." />' + '<br>' + '<button type="submit">submit</button>' + '</form>'; res.send(html); }); app.post('/information', function(req, res){ var username = req.body.username; var html = 'hello: ' + username + '.<br>' + '<a href="/information">try again.</a>'; res.send(html); }); var frm = '<form action="/file" method="post" enctype="multipart/form- data">' + '<br/>'+ '<input type="file" name="uploadfile" />' + '<br/>' + '<input type="submit" />' + '</form>'; app.get('/file',function(req,res){ res.send(frm); }); app.post('/file',function(req,res){ fs.readfile(req.body.uploadfile.path , function (err, data) { var filename = req.body.uploadfile.name; if(!filename){ console.log("there error") res.redirect("/file"); res.send(); } else { var newpath = "/uploads/" + filename; /// write file uploads folder fs.writefile(newpath, data, function (err) { /// let's see res.redirect("/uploads/" + filename); }); } }); }); /// show files app.get('/uploads/:file', function (req, res){ file = req.params.file; var img = fs.readfilesync("/uploads/" + file); res.send(img, 'binary'); });app.listen(process.env.port || 3003);
there's few things wrong here:
- the
enctype
value in form has spaces in middle (multipart/form- data
) - the
busboy
middleware not being used @ all,body-parser
middleware being used, not supportmultipart/form-data
. busboy
not populatereq.body
. if want kind of api, should @multer
, built onbusboy
providesreq.body
.
Comments
Post a Comment