node. js uploads images via Ajax _php Tutorial

Source: Internet
Author: User

node. js uploads images via Ajax


This stage, the use of the rest of the night with Node.js+mongdb+express+jade to achieve their own blog site, the blog in the post need to upload images, embedded in their own textarea tag implementation of the Markdown editor. This partial realization uses the Formdata function of HTML5 to realize

HTML code (JADE):

 
  
  
  1. Form#uploadfile
  2. Div.form-group
  3. Input#inputfile (type= "file" Name= "Inputfile")
  4. P.help-block#upfiletip only supports image uploads in PNG and IPG formats
  5. Button.btn.btn-success (type= "button" onclick= "Upfile ()") upload

Ajax code (JavaScript):

 
 
  1. Determine if the format of the picture is a PNG/IPG format
  2. function Judgephotoext (name) {
  3. if (name.length = = = 0) {
  4. $ ("#upfiletip"). CSS ("Color", "red");
  5. $ ("#upfiletip"). Text = "You did not select any pictures!!!" "
  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 format are supported!!!"
  12. return false;
  13. }
  14. return true;
  15. }

  16. Upload 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+ "! [Photo Tip] ("+data+") ";
  36. $ ("#content-textarea"). val (text);
  37. $ (' #imageModal '). Modal (' hide ');
  38. },
  39. Error:function (Err) {
  40. Console.log (ERR);
  41. }
  42. })
  43. }
  44. }
Note: It is important to note that the ProcessData property is set to False, this is the property of HTML5, and if it is not set to false, this place will have a problem. The main is that the contents of the file do not want to be converted into strings. See the parameter explanation of jquery Ajax in detail: http://www.w3school.com.cn/jquery/ajax_ajax.asp

For the Formdata object, you can first create an empty Formdata object and then use the Append () method to add a field to the object (referring to a description of another site)
Like what:

 
  
  
  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. // The file selected by the user is already included in Fileinputelement
  5. omyform.append ("UserFile", Fileinputelement.files[0]);

  6. var ofilebody = "hey!";//Blob object contains file contents
  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 the content needs to see 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; Reserved suffix
  5. Form.maxfieldssize = 4*1024*1024; File size
  6. Form.parse (Req,function (err,fields,files) {
  7. if (err) {
  8. Res.send ("Insert tag failed");
  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 support image files in PNG and JPG formats");
  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 formidable library-assisted implementations

In fact, the most important is the use of formdata, with HTML5 to achieve this part of the asynchronous upload or relatively convenient

http://www.bkjia.com/PHPjc/1114324.html www.bkjia.com true http://www.bkjia.com/PHPjc/1114324.html techarticle node. js uploads images through Ajax this stage, using the rest of the night to use the Node.js+mongdb+express+jade to achieve their own blog site, the blog in the post need to use the 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.