将图像保存为base64并使用rout返回它

时间:2017-07-28 08:43:59

标签: javascript node.js angular express multer

我对使用NodeJS有点新意,这是我第一次创建API,我将带有angular和ng-file-upload的图像上传到服务器,其想法是api收到一个文件,将其编码为base64,然后给我一个带有图像路径的对象,然后在客户端显示它。

config.js

'use strict'

const express = require('express');
const bodyParser = require('body-parser');
const app = express();
const multer = require('multer');
const fs = require('fs-extra');

app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());

app.use(function(req, res, next) {
  res.header("Access-Control-Allow-Origin", "*");
  res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept, Authorization");
  res.header("Access-Control-Allow-Methods", "GET,HEAD,POST,PUT,DELETE");
  next();
});

app.use('/uploads', express.static("./uploads"));
app.use(bodyParser.json());

var storage = multer.diskStorage({ //multers disk storage settings
  destination: function (req, file, cb) {
    let ind = file.mimetype.indexOf('/');
    let type = file.mimetype.slice(0, ind);
    let path = `./uploads/${type}`;
    fs.mkdirsSync(path);
    cb(null, path);
  },
  filename: function (req, file, cb) {
    var datetimestamp = Date.now();
    var ind = file.originalname.indexOf('.');
    var filename = file.originalname.slice(0 , ind);
    cb(null, filename+ '-' + datetimestamp + '.' + file.originalname.split('.')[file.originalname.split('.').length -1])
  }
});

var upload = multer({ //multer settings
              storage: storage
            }).single('avatar', 12);
/** API path that will upload the files */

app.post('/upload', function(req, res) {
  upload(req,res,function(err){
  if(err){
   res.json({error_code:1,err_desc:err});
   return;
  }
    res.json(req.file);
    console.log(req.file)
  });
});

我该怎么做,我使用express和multer来上传文件。 这个想法是这样的"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAGQAAABkCAYAAABw4pVUAAAACXBIWXMAAAPoAAAD6AG1e1JrAAAgAElEQV"

0 个答案:

没有答案