Nodejs+multer+ajax File Upload

Source: Internet
Author: User

Front-end HTML code + AJAX code

Form form (do not specify action)

<form enctype= "Multipart/form-data" method= "post" class= "Upload-cont" >    <input type= "file" Name= "Files1 "class=" Files1 ">    <input type=" text "name=" username "class=" username ">    <input type=" button " class= "UPLOADBTN" value= "click to upload" ></form>

Uploading files using Ajax in jquery

<script src= "Http://apps.bdimg.com/libs/jquery/2.1.4/jquery.min.js" ></script><script>
$ (". Files1"). On ("Change", function (e) {     var e = e | | window.event;     var files = e.target.files;     var file = files[0];    File Upload    $ (". Uploadbtn"). Off ("click"). On ("click", Function () {         var username = $ ('. Username '). Val ();         var formData = new FormData ();         Formdata.append (' files1 ', file);         Formdata.append (' username ', username);         Console.log (file);         $.ajax ({              URL: "/ajaxupload",              type: "Post",              Data:formdata,              contenttype:false,              Processdata:false,              success:function (res) {                   console.log (res);              },              error:function (err) {                   Console.log (err);              }       );   })
})
</script>

Formdata Object Introduction https://developer.mozilla.org/zh-CN/docs/Web/API/FormData/Using_FormData_Objects

The Formdata object allows you to assemble a set XMLHttpRequest of key/value pairs that are sent by request. It can be more flexible and convenient to send form data, because it can be used independently of the form.

If you set the form's encoding type to multipart/form-data, the data format transmitted through Formdata is the submit() same as the data format that the form transmits through the method.

So when you use Formdata, you only need to set enctype= "Multipart/form-data" on the form, and then use Ajax and Formdata to submit form form data, instead of directly using form form submit Submission method.

Multer Introduction

Multer is a node. js middleware that handles multipart/form-data types of form data, which is used primarily for uploading files. It is written on busboy very efficient.

Note : Multer does not process any non- multipart/form-data type form data.

Multer Document Address: Https://www.npmjs.com/package/multer
Reference Address: Https://github.com/expressjs/multer/blob/master/doc/README-zh-cn.md

Install Multer under Windows

NPM Install--save Multer

Use of Multer

var multer = require (' Multer ');
/**
* PROCESS.CWD () Gets the project root address, you can assign the uploaded file to the static file directory, and then return the address to the front-end page, such as:
* var Uploadpath = PROCESS.CWD () + '/public/uploads ' front-end access address http://localhost:3000/uploads/file name
**/
var Uploadpath = process.cwd () + '/uploads ';//stored directly in the root directory uploads
var storage = Multer.diskstorage ({//multer storage engine storage Engine Custom Reference Https://github.com/expressjs/multer/blob /MASTER/STORAGEENGINE.MD ,//Specify the path of the uploaded file
Filename:function (req, file, CB) {CB (NULL, File.fieldname + '-' +

Storage:storage,
Limits: '//limits of the uploaded data
}). single (' files1 ');//single file Upload, files1 name of the Name field to accept the file in form form
App.post ('/ajaxupload ', function (req,res) {
Multer (Req,res,function (err) {
if (err) {
Console.log (ERR);
return;
}
Console.log (req.body.username);//Get Data Name= "username" from a field in a form in Formdata
Req.body non-file data submitted by Ajax
Req.body.username//Submit parameter username
Req.file.fieldname upload file input filename field name
Req.file.filename upload file filename
Req.file.originalname upload file filename
Req.file.mimetype Upload file types
Req.file.size Upload File size
Req.file.destination the path to the upload file exists
Req.file.path the path of the uploaded file
Console.log (Req.file.path);

/**

* You can do a file upload filter by req.file parameters, such as req.file.size limit file upload size, req.file.mimetype limit file upload type

**/

Res.send ({msg: ' upload success ', img:req.file.path});//return data to the front page, you can upload the picture, preview in front.
})
});
When you use Res.send () to send data to the front end, the address shown here is D:\leijie\test\express-mysql\uploads\share.png because the image of this article is stored in the project root directory.

Static directory settings are set in the App.js file App.use (express.static (Path.join (__dirname, ' public '));

RELATED links:

Https://www.npmjs.com/package/multer

Https://github.com/expressjs/multer/blob/master/doc/README-zh-cn.md

Https://developer.mozilla.org/zh-CN/docs/Web/API/FormData/Using_FormData_Objects

Https://github.com/expressjs/multer/blob/master/StorageEngine.md

Https://developer.mozilla.org/zh-CN/docs/Web/API/XMLHttpRequest/Using_XMLHttpRequest

Nodejs+multer+ajax File Upload

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.