Node. js uploads images through ajax
In this phase, the node is used for the remaining time in the night. js + mongdb + express + jade to implement a blog website of your own. You need to upload images to post a blog and embed them in the markdown editor implemented by using the textarea tag. This part of implementation is implemented using the formData function of html5.
Html code (jade ):
- Form # uploadfile
- Div. form-group
- Input # inputfile (type = "file" name = "inputfile ")
- P. help-block # upfiletip only supports uploading images in png and ipg formats
- Button. btn. btn-success (type = "button" onclick = "upFile ()") Upload
Ajax code (javascript ):
- // Determine whether the image format is png/ipg
- Function judgePhotoExt (name ){
- If (name. length = 0 ){
- $ ("# Upfiletip" ).css ("color", "red ");
- $ ("# Upfiletip"). text = "You have not selected any images !!! "
- Return false;
- }
- Var extName = name. substring (name. lastIndexOf ('.'), name. length). toLowerCase ();
- If (extName! = '.Png '& extName! = '. Ipg '){
- $ ("# Upfiletip" ).css ("color", "red ");
- $ ("# Upfiletip"). text = "only files in png and ipg formats are supported !!! "
- Return false;
- }
- Return true;
- }
- // Upload an image file
- Function upFile (){
- Var filename = $ ("# inputfile"). val ();
- If (judgePhotoExt (filename )){
- Var data = new FormData ();
- Var files = $ ("# inputfile") [0]. files;
- If (files ){
- Data. append ("file", files [0]);
- }
- $. Ajax ({
- Url: '/blog/photo/new ',
- Type: 'post ',
- Data: data,
- Async: false,
- Cache: false,
- ContentType: false,
- ProcessData: false,
- Success: function (data ){
- Var text = $ ("# content-textarea"). val ();
- Text = text + "! [Image prompt] ("+ data + ")";
- $ ("# Content-textarea"). val (text );
- $ ('# Imagemodal'). modal ('hide ');
- },
- Error: function (err ){
- Console. log (err );
- }
- })
- }
- }
Note: The processData attribute must be set to false, which is an html5 attribute. If it is not set to false, a problem may occur. The main reason is that the file content does not want to be converted into a string. See the jquery ajax parameter description: http://www.w3school.com.cn/jquery/ajax_ajax.asp
For a FormData object, you can first create an empty FormData object, and then use the append () method to add fields to the object (reference the descriptions of other websites)
For example:
- Var oMyForm = new FormData ();
- OMyForm. append ("username", "Groucho ");
- OMyForm. append ("accountnum", 123456); // The number 123456 is immediately converted to the string "123456"
- // FileInputElement already contains the selected file
- OMyForm. append ("userfile", fileInputElement. files [0]);
- Var oFileBody = "<a id =" a "> <B id =" B "> hey! "; // The file content contained in the Blob Object
- Var oBlob = new Blob ([oFileBody], {type: "text/xml "});
- OMyForm. append ("webmasterfile", oBlob );
- Var oReq = new XMLHttpRequest ();
- OReq. open ("POST", "http://foo.com/submitform.php ");
- OReq. send (oMyForm );
This part of content needs to view the specific content of the FormData object, you can view the URL: http://www.cnblogs.com/lhb25/p/html5-formdata-tutorials.html
The node. js background code is as follows:
- Router. post ('/photo/new', function (req, res, next ){
- Let form = new formidable. IncomingForm (); // create an upload form
- Form. uploadDir = UPLOAD_PATH;
- Form. keepExtensions = true; // retain the suffix
- Form. maxFieldsSize = 4*1024*1024; // File Size
- Form. parse (req, function (err, fields, files ){
- If (err ){
- Res. send ("failed to insert tag ");
- Return;
- }
- Let extName = '';
- Let urls = [];
- For (var key in files ){
- Let file = files [key];
- Switch (file. type ){
- Case 'image/pjpeg ':
- ExtName = 'jpg ';
- Break;
- Case 'image/jpeg ':
- ExtName = 'jpg ';
- Break;
- Case 'image/png ':
- ExtName = 'png ';
- Case 'image/x-png ':
- ExtName = 'png ';
- Break;
- }
- If (extName. length = 0 ){
- Res. send ("only images in png and jpg formats are supported ");
- Return;
- }
- Let saveName = uuid. v1 () + '.' + extName;
- Let savePath = form. uploadDir + saveName;
- Urls. push (PHOTO_URL + saveName );
- Fs. renameSync (file. path, savePath );
- }
- Res. send (urls [0]);
- })
- })
Using the formidable Library
In fact, the most important thing is the use of FormData. using html5 to implement this part of asynchronous upload is more convenient.