There are two ways for Nodejs to upload images: nodejs

Source: Internet
Author: User
Tags file url

There are two ways for Nodejs to upload images: nodejs

Node: the first method for uploading images

1. first introduce the module "connect-multiparty ":"~ 1.2.5 ",

Add "connect-multiparty" to package. json ":"~ 1.2.5 ",

Switch to the project directory in the command, and run the npm command: npm installl;

Basic configuration complete

Index.html

<! DOCTYPE html> 

 

The red part of app. js is the uploaded Image Code.

 

Var express = require ('express '); var path = require ('path'); var favicon = require ('static-favicon '); var logger = require ('Morgan '); var cookieParser = require ('cookie-parser'); var bodyParser = require ('body-parser '); var ejs = require ('ejs'); var routes = require ('. /routes/Index'); var users = require ('. /routes/users '); var upload = require ('. /routes/upload'); var uploadtupian = require ('. /routes/uploadtupian' ); Var test = require ('. /routes/test'); var multer = require ("multer"); var app = express (); var flash = require ('connect-flash '); var md5 = require ('md5'); var fs = require ('fs'); var multipart = require ('connect-multipart '); // view engine setup // view engine setupapp. set ('view', path. join (_ dirname, 'views'{};app.engine('.html ', ejs. _ express); app. set ('view engine ', 'html'); app. use (flash (); // cross-origin request app. all ('*', Function (req, res, next) {res. header ('access-Control-Allow-origin', '*'); res. header ('access-Control-Allow-headers', 'content-Type, Content-Length, Authorization, Accept, X-Requested-With, yourheaderfeild'); res. header ('access-Control-Allow-Methods ', 'Put, POST, GET, DELETE, options'); if (req. method = 'options') {res. send (200) ;}else {next () ;}}); app. use (favicon (); app. use (logger ('dev ')); App. use (bodyParser. json (); app. use (bodyParser. urlencoded (); app. use (cookieParser (); app. use (express. static (path. join (_ dirname, 'public');/* app. use (express. bodyParser ({uploadDir :'. /public /. images '}); */app. use ('/', routes); app. use ('/users', users); app. use ('/test', test); app. use ('/up', upload); app. use ('/uploadtupian', uploadtupian); app. post ('/upload', multipart (), function (req, res) {console. log (re Q. body. name); // get filename var filename = req. files. files. originalFilename | path. basename (req. files. files. ws. path); // copy file to a public directory // modify the file name console. log (filename); var newname = 56; var targetPath = path. dirname (_ filename) + '/public/images/' + filename; // copy file fs. createReadStream (req. files. files. ws. path ). pipe (fs. createWriteStream (targetPath); var newname = path. dirname (_ f Ilename) + '/public/images/'{newname}'.jpg'; filename = fs. rename (targetPath, newname, function (err) {if (err) {console. log ('renaming failed');} else {console. log ("renamed") ;}}); // return file url res. json ({code: 200, msg: {url: 'http: // '+ req. headers. host + '/' + newname});/* app. post ('/file-upload', function (req, res) {console. log (req); // obtain the temporary file path var tmp_path = req. files. thumbnail. path; // specify the directory after the file is uploaded-Example: "Images" directory. Var target_path = '. /public/images/'+ req. files. thumbnail. name; // move the file fs. rename (tmp_path, target_path, function (err) {if (err) throw err; // Delete the Temporary Folder file, fs. unlink (tmp_path, function () {if (err) throw err; res. send ('file uploaded to: '+ target_path +'-'+ req. files. thumbnail. size + 'bytes ') ;}); */app. use ('/upload', function (req, res) {res. render ('upload', {title: "file production"}) ;}); // catch 404 and forwarding to error handlerapp. use (function (req, res, next) {var err = new Error ('not found'); err. status = 404; next (err) ;});/* // file length app. use (multer ({dest :'. /public/images ', rename: function (fieldname, filename) {return filename ;}})) * /// error handlers // development error handler // will print stacktraceif (app. get ('enabled') = 'development') {app. use (function (err, req, res, next) {res. status (err. status | 500); res. render ('error', {message: err. message, error: err});} // production error handler // no stacktraces leaked to userapp. use (function (err, req, res, next) {res. status (err. status | 500); res. render ('error', {message: err. message, error :{}}) ;}; module. exports = app;

 

Upload.html

<! DOCTYPE html> 

Ii. upload multiple groups of photos

Import module "formidable": "1.1.1"

Add "formidable": "1.1.1" to package. json ";

Package. json

{  "name": "application-name",  "version": "0.0.1",  "private": true,  "scripts": {    "start": "nodejs ./bin/www"  },  "dependencies": {    "express": "~4.0.0",    "static-favicon": "~1.0.0",    "morgan": "~1.0.0",    "cookie-parser": "~1.0.1",    "body-parser": "~1.0.0",    "debug": "~0.7.4",    "ejs": "~0.8.5",    "multer":"0.1.6",    "connect-flash": "0.1.1",    "md5":"^2.1.0", "connect-multiparty": "~1.2.5", "formidable":"1.1.1"  }}

Main Code

app.use('/', routes);app.use('/users', users);app.use('/test', test);app.use('/up',upload);app.use('/uploadtupian',uploadtupian);

And then in the router folder

Create uploadtupian. js

Var express = require ('express '); var router = express. router ();/* GET home page. */router. get ('/', function (req, res) {res. render ('up', {title: 'upload multiple sets of pictures '}) ;}); module. exports = router;

Then, under the view folder

New up.html

<! DOCTYPE html> 

App. js

Add app. use ('/up', upload );

Add

Upload. js File

var express =require('express');var path = require('path');var router =express.Router();var formidable=require('formidable');var fs=require('fs');router.post('/',function(req,res,next){console.log(req.body);var form=new formidable.IncomingForm();form.uploadDir='/tmp';form.keepExtensions=true;var targetDir=path.join(__dirname,'../public/upload');fs.access(targetDir,function(err){if(err){fs.mkdirSync(targetDir);}_fileParse();});function _fileParse(){form.parse(req,function(err,fields,files){console.log(fields);          if(err) throw err;          var fileUrl=[];          var errCount=0;          var keys=Object.keys(files);          keys.forEach(function(key){             var filePath=files[key].path;             var fileExt=filePath.substring(filePath.lastIndexOf('.'));             if(('.jpg.jpeg.png.gif').indexOf(fileExt.toLowerCase())==-1){             errCount+=1;             }             else{             var fileName=new Date().getTime()+fileExt;             var targetFile=path.join(targetDir,fileName);             //                   fs.renameSync(filePath,targetFile);                   fileUrl.push('/upload'+fileName);             }          })                    res.json({fileUrl:fileUrl,success:keys.length-errCount, error:errCount})})}})module.exports=router;

Now we have completed two methods for uploading images by node.

 

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.