Home > Web Front-end > JS Tutorial > Angular2+nodejs creates image upload effect

Angular2+nodejs creates image upload effect

php中世界最好的语言
Release: 2018-04-19 13:41:16
Original
1529 people have browsed it

This time I will bring you the image upload effect of angular2 nodejs. What are the precautions for image upload effect of angular2 nodejs? The following is a practical case, let's take a look.

nodejs backend code

 代码如下    
varexpress = require("express");
//网络请求模块
varrequest = require("request");
//引入nodejs文件系统模块
const fs = require('fs');
//引入body-parser
//包含在请求正文中提交的键/值对数据。
//默认情况下,它是未定义的,并在使用body-parser中间件时填充。
varbodyParser = require('body-parser');
varapp = express();
//解析 application/x-www-form-urlencoded,limit:ཐmb'用于设置请求的大小
//解决nodejs Error: request entity too large问题
app.use(bodyParser.urlencoded({ limit:ཐmb',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){
  varimgData = req.body.url;
  varbase64Data = imgData.replace(/^data:image\/\w+;base64,/,"");
  vardataBuffer =newBuffer(base64Data,'base64');
  fs.writeFile("image.png", dataBuffer,function(err) {
    if(err){
      res.send(err);
    }else{
      res.send("保存成功!");
    }
  });
})
 
varserver = app.listen(4444,function() {
  console.log('监听端口 4444');
});
Copy after login
angular2 frontend code

//上传图片
 /*
 *   let data = {
 *    size: �',
 *    type: 'image/jpeg',
 *    name: 'test.jpg',
 *    url: base64
 *   };
 *获取图片的base64码可以通过FileReader获取
 */
 uploadImage(data) {
  returnnewPromise((resolve, reject) => {
   let headers =newHeaders({
    'Content-Type':'application/x-www-form-urlencoded'
   });
   let options =newRequestOptions({
    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 keyinobj) {
    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));
    }
  }
   returnresult.join('&');
  }
  private toQueryPair(key, value) {
   if(typeofvalue =='undefined') {
    returnkey;
   }
   returnkey +'='+ encodeURIComponent(value ===null?'': String(value));
  }
Copy after login
I believe you have mastered the method after reading the case in this article. For more exciting information, please pay attention to other related articles on the PHP Chinese website!

Recommended reading:

JS implementation of drop-down menu login registration pop-up window

How to deal with http hijacked floating ads

Summary of methods to improve Node.js performance

The above is the detailed content of Angular2+nodejs creates image upload effect. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template