一, 接受上传的图片
需要用到const multipart = require('connect-multiparty')
具体案例如下我觉得是目前最简单的:
router.post('/uploadPicLetH',multipart(),(req,res)=>{
let filename = Date.parse(new Date());
let filesType = req.files.letHousePic.type.split('/')[1] || "png";
let targetPath = './public/uploads/letHousePic/' + filename+'.'+filesType;
let logoUrl = '/uploads/letHousePic/' + filename+'.'+filesType
fs.createReadStream(req.files.letHousePic.path).pipe(fs.createWriteStream(targetPath));
//响应ajax请求,告诉它图片访问地址
res.json({ code: 200, url: 'http://' + req.headers.host + logoUrl,uid:filename,name:filename+'.'+filesType});
})
二,复制图片
let fs = require('fs');
let path = require('path');
let fileName = '123.jpg'
let sourceFile = path.join(__dirname+'/public/upload/tt01/', fileName)
let destPath = path.join(__dirname, "/public/upload/tt02/", fileName)
console.log(__dirname)
let readStream = fs.createReadStream(sourceFile)
let writeStream = fs.createWriteStream(destPath)
readStream.pipe(writeStream)
三,移动图片
var fs = require('fs');
var path = require('path');
var fileName = "123.png";
var sourceFile = path.join(__dirname, fileName);
var destPath = path.join(__dirname, "要移到的路径", fileName);
fs.rename(sourceFile, destPath, function (err) {
if (err) throw err;
fs.stat(destPath, function (err, stats) {
if (err) throw err;
console.log('stats: ' + JSON.stringify(stats));
});
});