Node. js + angular2 sample code sharing for Image Upload

Source: Internet
Author: User
This article mainly introduces angular2 + nodejs to implement the image upload function, which has some reference value, interested friends can refer to this article mainly introduced angular2 + nodejs implementation # css/css-rwd-images.html "target =" _ blank "> image upload function, has a certain reference value, for more information, see

When using angular2 to upload images, you may encounter various problems. After multiple attempts, the image will be uploaded successfully. I will share my methods with you:

Nodejs background code

Var express = require ("express"); // network request module var request = require ("request "); // introduce the nodejs file system module const fs = require ('fs'); // introduce the body-parser // key/value pair data that is included in the request body. // By default, it is undefined and filled with body-parser middleware. Var bodyParser = require ('body-parser '); var app = express (); // parse application/x-www-form-urlencoded, limit: '20mb' is used to set the request size // solve the nodejs Error: request entity too large issue app. use (bodyParser. urlencoded ({limit: '20mb', extended: true}); // sets the cross-origin access app. all ('*', function (req, res, next) {res. header ("Access-Control-Allow-Origin", "*"); res. header ("Access-Control-Allow-Headers", "X-Requested-With"); res. header (" Access-Control-Allow-Methods "," PUT, POST, GET, DELETE, OPTIONS "); res. header ("Content-Type", "application/json; charset = UTF-8"); next () ;}); // upload the image app. post ('/upload', function (req, res) {var imgData = req. body. url; var base64Data = imgData. replace (/^ data: image \/\ w +; base64,/, ""); var dataBuffer = new Buffer (base64Data, 'base64'); fs. writeFile ("image.png", dataBuffer, function (err) {if (err) {res. send (err );} Else {res. send ("saved successfully! ") ;}}) ;}) Var server = app. listen (4444, function () {console. log ('listener port 4444 ');});

Angular2 front-end code

// Upload an image/** let data = {* size: '000000', * type: 'image/jpeg ', * name: 'test.jpg', * url: base64 *}; * You can use FileReader to obtain the base64 code of an image. */uploadImage (data) {return new Promise (resolve, reject) ==>{ let headers = new Headers ({'content-type': 'application/x-www-form-urlencoded '}); let options = new RequestOptions ({headers: headers}); this. http. post (" http://localhost:4444/upload ", This. toQueryString (data), options ). map (res => res. json ()). subscribe (data =>{ resolve (data), error =>{ reject (error) }})} // serialize private toQueryString (obj) with JSON Parameters) {let result = []; for (let key in obj) {key = encodeURIComponent (key); let values = obj [key]; if (values & values. constructor = Array) {let queryValues = []; for (let I = 0, len = values. length, value; I <len; I ++) {value = Values [I]; queryValues. push (this. toQueryPair (key, value);} result = result. concat (queryValues);} else {result. push (this. toQueryPair (key, values) ;}} return result. join ('&');} private toQueryPair (key, value) {if (typeof value = 'undefined') {return key ;} return key + '=' + encodeURIComponent (value = null? '': String (value ));}

The above is the sample code for nodejs + angular2 to implement the image upload function. For more information, see other related articles in the first PHP community!

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.