当前位置:主页 > 网页前端 > AngularJS >

angular2+nodejs实现图片上传功能

时间:2021-01-19 12:06:17 | 栏目:AngularJS | 点击:

在使用angular2进行图片上传的时候,遇到了各种各样的问题。在多番尝试之后最终成功上传图片,下面将我的方法分享给大家:

nodejs 后台代码

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前台代码

 //上传图片
 /*
 *   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('&');
  }
  private toQueryPair(key, value) {
   if (typeof value == 'undefined') {
    return key;
   }
   return key + '=' + encodeURIComponent(value === null ? '' : String(value));
  } 

您可能感兴趣的文章:

相关文章