Node. js uploads images through ajax

Source: Internet
Author: User

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 ):

 
 
  1. Form # uploadfile
  2. Div. form-group
  3. Input # inputfile (type = "file" name = "inputfile ")
  4. P. help-block # upfiletip only supports uploading images in png and ipg formats
  5. Button. btn. btn-success (type = "button" onclick = "upFile ()") Upload
Ajax code (javascript ):

 
 
  1. // Determine whether the image format is png/ipg
  2. Function judgePhotoExt (name ){
  3. If (name. length = 0 ){
  4. $ ("# Upfiletip" ).css ("color", "red ");
  5. $ ("# Upfiletip"). text = "You have not selected any images !!! "
  6. Return false;
  7. }
  8. Var extName = name. substring (name. lastIndexOf ('.'), name. length). toLowerCase ();
  9. If (extName! = '.Png '& extName! = '. Ipg '){
  10. $ ("# Upfiletip" ).css ("color", "red ");
  11. $ ("# Upfiletip"). text = "only files in png and ipg formats are supported !!! "
  12. Return false;
  13. }
  14. Return true;
  15. }

  16. // Upload an image file
  17. Function upFile (){
  18. Var filename = $ ("# inputfile"). val ();
  19. If (judgePhotoExt (filename )){
  20. Var data = new FormData ();
  21. Var files = $ ("# inputfile") [0]. files;
  22. If (files ){
  23. Data. append ("file", files [0]);
  24. }
  25. $. Ajax ({
  26. Url: '/blog/photo/new ',
  27. Type: 'post ',
  28. Data: data,
  29. Async: false,
  30. Cache: false,
  31. ContentType: false,
  32. ProcessData: false,
  33. Success: function (data ){
  34. Var text = $ ("# content-textarea"). val ();
  35. Text = text + "! [Image prompt] ("+ data + ")";
  36. $ ("# Content-textarea"). val (text );
  37. $ ('# Imagemodal'). modal ('hide ');
  38. },
  39. Error: function (err ){
  40. Console. log (err );
  41. }
  42. })
  43. }
  44. }
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:

 
 
  1. Var oMyForm = new FormData ();

  2. OMyForm. append ("username", "Groucho ");
  3. OMyForm. append ("accountnum", 123456); // The number 123456 is immediately converted to the string "123456"

  4. // FileInputElement already contains the selected file
  5. OMyForm. append ("userfile", fileInputElement. files [0]);

  6. Var oFileBody = "<a id =" a "> <B id =" B "> hey! "; // The file content contained in the Blob Object
  7. Var oBlob = new Blob ([oFileBody], {type: "text/xml "});

  8. OMyForm. append ("webmasterfile", oBlob );

  9. Var oReq = new XMLHttpRequest ();
  10. OReq. open ("POST", "http://foo.com/submitform.php ");
  11. 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:

 
 
  1. Router. post ('/photo/new', function (req, res, next ){
  2. Let form = new formidable. IncomingForm (); // create an upload form
  3. Form. uploadDir = UPLOAD_PATH;
  4. Form. keepExtensions = true; // retain the suffix
  5. Form. maxFieldsSize = 4*1024*1024; // File Size
  6. Form. parse (req, function (err, fields, files ){
  7. If (err ){
  8. Res. send ("failed to insert tag ");
  9. Return;
  10. }
  11. Let extName = '';
  12. Let urls = [];
  13. For (var key in files ){
  14. Let file = files [key];
  15. Switch (file. type ){
  16. Case 'image/pjpeg ':
  17. ExtName = 'jpg ';
  18. Break;
  19. Case 'image/jpeg ':
  20. ExtName = 'jpg ';
  21. Break;
  22. Case 'image/png ':
  23. ExtName = 'png ';
  24. Case 'image/x-png ':
  25. ExtName = 'png ';
  26. Break;
  27. }
  28. If (extName. length = 0 ){
  29. Res. send ("only images in png and jpg formats are supported ");
  30. Return;
  31. }
  32. Let saveName = uuid. v1 () + '.' + extName;
  33. Let savePath = form. uploadDir + saveName;
  34. Urls. push (PHOTO_URL + saveName );
  35. Fs. renameSync (file. path, savePath );
  36. }
  37. Res. send (urls [0]);
  38. })
  39. })

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.

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.