前端传过来的图片是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