nodejs 保存上传文件 发表于 2020-10-12 更新于 2020-11-25 评论数: 0 阅读次数: 本文字数: 1.3k 阅读时长 ≈ 1 分钟 nodejs 保存上传文件我用的是thinkjs搭建的项目。 功能实现是一样的。 123456789101112131415161718192021222324252627282930313233343536import {think} from "thinkjs";import fs from 'fs';import * as path from 'path';/** * 保存文件 * @param filename // 文件名 * @param tempPath // 上传的临时文件路径 * @param base64 // base64 字符串 * @param prefix - 文件夹前缀 */export async function saveFile(filename: string, tempPath: string, base64?: string, prefix: string = 'static/upload') { // 将 fs.rename promise 化 const renameFile = think.promisify(fs.rename, fs); // 文件保存目录 const savePath = think.config('UPLOAD_PATH'); // 创建文件夹 // fs.mkdir think.mkdir(savePath); // 文件后缀 const suffix = filename.split('.').pop(); // 对文件名进行过滤 const name = filename.split('.').shift().replace(/[\s\\\/,.*@#$%^&\|""“”::]/gi, ''); const newname = `${name}_${Date.now()}.${suffix}`; // 如果是base64 文件的话 进行转buffer保存 if (base64) { base64 = base64.replace(/^data:\w+\/\w+;base64,/, ''); const buffer = new Buffer(base64, 'base64'); fs.writeFileSync(path.join(savePath, newname), buffer); } else { // 直接移动文件保存 await renameFile(tempPath, path.join(savePath, newname)); } // 返回文件资源链接 return `${think.config('BASE_URL')}/${prefix}/${newname}`;}