node.js图片的上传、删除、移动与复制

const multer = require('multer');
const fs = require("fs");
const path = require('path');

/**
 * 文件上传
 * 参数说明:接收一个 options 对象作为参数,该对象包含三个属性
 * - path:图片上传路径
 * - key:与前端 formData 对象的 fieldname 相匹配(即 formData.append()方法的第一个参数)
 * - size: 设置图片最大限制,单位 kb
 */
function uploadFiles (options = {}) {
    // 1. 对参数 options 进行解构并设置默认值
    const { path = "./public/temp", key = "file", size = 1000 } = options;
    // 2. 设置 multer 的参数,配置 diskStorage,来控制文件存储的位置以及文件名字等
    const storage = multer.diskStorage({
        // 2.1 确定图片存储的位置
        destination: function (req, file, cb) {
            // 当 path 所对应目录不存在时,则自动创建该文件
            try {
                fs.accessSync(path);
            } catch (error) {
                fs.mkdirSync(path);
            }
            cb(null, path);
        },
        // 2.2 确定图片存储时的名字。(注意:如果使用原名,可能会造成再次上传同一张图片的时候的冲突)
        filename: function (req, file, cb) {
            var changedName = new Date().getTime() + '-' + file.originalname;
            cb(null, changedName);
        }
    });
    // 3. 配置图片限制
    const limits = {
        // 限制文件大小 100 kb
        fileSize: 3000 * size,
        // 限制文件数量
        files: 5
    };
    // 4.生成的专门处理上传的一个工具,可以传入 storage、limits 等配置
    const upload = multer({ storage, limits });
    // 5. 返回多文件上传的设置信息(同样可用于单文件上传)
    return upload.array(key);
}


/**
 * 复制文件
 * 参数说明: 接收一个 options 对象作为参数,该对象包含三个属性
 * - fromPath:源文件路径
 * - toPath:要复制过去的新路径
 * - filename:文件名
 */
function copyFiles (options = {}) {
    // 对参数进行解构,并设置默认值
    const { fromPath = './public/temp/', toPath = "./public/images/", filename } = options;
    let sourceFile = path.join(fromPath, filename);
    let destPath = path.join(toPath, filename);
    // 当 toPath 所对应目录不存在时,则自动创建该文件
    try {
        fs.accessSync(toPath);
    } catch (error) {
        fs.mkdirSync(toPath);
    }
    let readStream = fs.createReadStream(sourceFile);
    let writeStream = fs.createWriteStream(destPath);
    readStream.pipe(writeStream);
}

/**
 * 移动文件
 * 参数说明: 接收一个 options 对象作为参数,该对象包含三个属性
 * - fromPath:源文件路径
 * - toPath:要复制过去的新路径
 * - filename:文件名
 */
function moveFiles (options = {}) {
    // 对参数进行解构,并设置默认值
    const { fromPath = './public/temp/', toPath = "./public/images/", filename } = options;
    var sourceFile = path.join(fromPath, filename);
    var destPath = path.join(toPath, filename);
    // 当 toPath 所对应目录不存在时,则自动创建该文件
    try {
        fs.accessSync(toPath);
    } catch (error) {
        fs.mkdirSync(toPath);
    }
    fs.renameSync(sourceFile, destPath);
    return { path: destPath };
}

/**
 * 删除文件
 * 参数说明: filePath 为要删除的文件路径
 */
function removeFiles (filePath = "./public/temp") {
    let stats = fs.statSync(filePath);
    // 判断是否是文件
    if (stats.isFile()) {
        // 删除文件
        fs.unlinkSync(filePath)
    } else if (stats.isDirectory()) {
        let filesArr = fs.readdirSync(filePath);
        filesArr.forEach(file => {
            removeFiles(path.resolve(filePath, file));
        })
        fs.rmdirSync(filePath);
    }
}



module.exports = { uploadFiles, copyFiles, moveFiles, removeFiles }

图片的上传

var express = require('express');
var router = express.Router();
const { uploadFiles } = require('../utils/handleFiles')

router.post('/uploadImages', function (req, res, next) {
    const uploadImages = uploadFiles({
        path: './public/temp',
        key: 'file',
    });
    uploadImages(req, res, err => {
        if (err) {
        } else {
            res.send({
                message: "上传成功",
                status: 1,
                data: req.files[0].filename
            })
        }
    })
});

module.exports = router;

图片的移动和删除缓存图片

module.exports.addSalesMen = async params => {
    const data = await addSalesMen(params);
    if (data._id) {
        //移动图片
        moveFiles({
            fromPath: './public/temp',
            toPath: './public/images',
            filename: params.images
        });
        //删除缓存图片
        removeFiles('./public/temp');
        return {
            message: "新增成功",
            status: 1,
            data
        }
    } else {
        return {
            message: "添加失败",
            status: 0,
        }
    }
}

前端调用(我这里使用的是element ui)

<div class="banner">
     <p>引导页3:</p>
     <el-upload
       class="avatar-uploader"
       :action="paths + '/images/uploadImages'"
       :show-file-list="false"
       :on-success="addbanner3"
     >
       <div v-if="uplist.banner3" class="banner_img">
         <img :src="paths + '/' + path + uplist.banner3" class="avatar" />
       </div>
       <i v-else class="el-icon-plus avatar-uploader-icon"></i>
     </el-upload>
 </div>


文件夹说明:

temp文件夹是缓存文件夹,用户在选择图片的时候或许会更换多张图片,实际只有一张,我们不可能将这些图片全存起来,所以暂时放在temp文件夹中,在点击确定之后,会清空temp文件夹,将选中的哪一张图片放在images文件夹中。

  • 1
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值