用express 写图片上传功能

前端传过来的图片是base64 

{
  img: 'base64...',
  key: 'sd'
}

 将存储图片的目录设置为 Express 的静态资源目录(使用 express.static 方法)。这样,存储图片的文件夹就可以被公开访问

const http = require("http");
const express = require("express");
const bodyParser = require("body-parser");
const morgan = require('morgan')
const fs = require('fs')
const path = require('path')

const router = require('./routers')
const app = express();

app.use(bodyParser.json({ limit: "50mb" }));
app.use(bodyParser.urlencoded({ extended: false }));

app.use(express.static('public/images'))
app.all("*", function (req, res, next) {
  // //设置允许跨域的域名, *代表允许任意域名跨域
  res.header("Access-Control-Allow-Origin", req.header.origin || "*");

  //允许的header类型
  res.header("Access-Control-Allow-Headers", "*");

  // 跨域允许的请求方式
  res.header("Access-Control-Allow-Methods", "PUT,GET,POST,DELETE,OPTIONS");

  res.header(`Cccess-Control-Allow-Credentials`, true);

  if (req.method == "OPTIONS") {
    res.sendStatus(200);
  } else {
    next();
  }
});

app.use('/apis', router)
const server = http.createServer(app);

const port = process.env.PORT || 8086; //服务器启动端口 生产环境
// const port = process.env.PORT || 8085; //服务器启动端口 测试环境
// const hostname = "0.0.0.0";
const hostname ="127.0.0.1"
server.listen(port, hostname);
console.log(`http server listening on http://${hostname}:${port}`);

 1.保存图片

2.返回前端可以直接访问的url,req.protocol + '://' + req.get('host') + imgname

注意:本人是公开访问public/images,所以imgname是在public/images目录下

const express = require('express')
const fs = require('fs')
const Router = express.Router();

Router.post('/updateImg', (req, res) => {
  let imgData = req.body.img;
  let base64Data = imgData.replace(/^data:image\/\w+;base64,/, '');
  let dataBuffer = Buffer.from(base64Data, 'base64')//新的用法 Buffer.from
  let imgPath = './public/images/template/img' + req.body.key + '.png'

  // 存图片
  function writeImg() {
    fs.writeFile(imgPath, dataBuffer, error => {
      if(error) {
        console.log(error);
        res.sendStatus(500)
      } else {
        const imageUrl = req.protocol + '://' + req.get('host') + '/template/img'  + req.body.key + '.png'
        res.send(imageUrl)
      }
    })
  }
  fs.access(imgPath, error => {
    if(!error) {
      //  如果文件存在,删除该文件后再保存
        fs.unlink(imgPath, error => {
            if(error) {
              console.log(error);
              res.sendStatus(500)
            } else {
              console.log(fs.existsSync(imgPath), "文件存在");
              writeImg()
            }
        })
       
    } else {
      writeImg()
    }
  })
})

module.exports = Router

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值