Home  >  Article  >  Web Front-end  >  Sample code sharing for nodejs+angular2 to implement image upload function

Sample code sharing for nodejs+angular2 to implement image upload function

黄舟
黄舟Original
2017-03-28 14:53:161198browse

This article mainly introduces the implementation of angular2+nodejsPicturesUpload function has certain reference value. Interested friends can refer to it

When using angular2 to upload images, I encountered various problems. After trying, I finally successfully uploaded the image. I will share my method with you below:

nodejs backend code

var express = require("express");
//网络请求模块
var request = require("request");
//引入nodejs文件系统模块
const fs = require('fs');
//引入body-parser
//包含在请求正文中提交的键/值对数据。 
//默认情况下,它是未定义的,并在使用body-parser中间件时填充。
var bodyParser = require('body-parser');
var app = express();
//解析 application/x-www-form-urlencoded,limit:'20mb'用于设置请求的大小
//解决nodejs Error: request entity too large问题
app.use(bodyParser.urlencoded({ limit:'20mb',extended: true })); 
//设置跨域访问
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();
});
//上传图片
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("保存成功!");
    }
  });
})

var server = app.listen(4444, function() {
  console.log('监听端口 4444');
});

angular2 frontend code

 //上传图片
 /*
 *   let data = {
 *    size: '125422',
 *    type: 'image/jpeg',
 *    name: 'test.jpg',
 *    url: base64
 *   };
 *获取图片的base64码可以通过FileReader获取
 */

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


// JSON参数序列化
  private toQueryString(obj) {
   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(&#39;&&#39;);
  }
  private toQueryPair(key, value) {
   if (typeof value == &#39;undefined&#39;) {
    return key;
   }
   return key + &#39;=&#39; + encodeURIComponent(value === null ? &#39;&#39; : String(value));
  }

The above is the detailed content of Sample code sharing for nodejs+angular2 to implement image upload function. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn