UNPKG

node-web-mvc

Version:
72 lines (71 loc) 2.2 kB
"use strict"; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", { value: true }); /** * @module MultipartFile * @description 上传的文件对象 */ const path_1 = __importDefault(require("path")); const fs_1 = __importDefault(require("fs")); const IllegalArgumentException_1 = __importDefault(require("../../errors/IllegalArgumentException")); const normalizePath = (source) => source.replace(/\\/g, '/'); class MultipartFile { /** * 判断当前文件内容是否为空 */ get isEmpty() { return this.size <= 0; } constructor(name, tempFile, mediaType, size, dir) { this.mediaType = mediaType; this.tempFile = tempFile; this.name = name; this.size = size; this.dir = dir; } validatePath(file) { file = normalizePath(path_1.default.normalize(file)); const cwd = normalizePath(process.cwd()); if (file.indexOf(cwd) > -1 && file.indexOf(this.dir) < 0) { // 非法写入 throw new IllegalArgumentException_1.default('Illegal write path: ' + file); } } /** * 将上传的文件保存到指定位置 */ async transferTo(dest) { if (!path_1.default.isAbsolute(dest)) { dest = path_1.default.join(this.dir, dest); } this.validatePath(dest); MultipartFile.ensureDirSync(path_1.default.dirname(dest)); // 写出文件 fs_1.default.renameSync(this.tempFile, dest); } static ensureDirSync(dir) { if (fs_1.default.existsSync(dir)) { return; } fs_1.default.mkdirSync(dir, { recursive: true }); } /** * 获取当前文件的,为byte[] */ async getBytes() { return fs_1.default.readFileSync(this.tempFile); } destory() { try { if (fs_1.default.existsSync(this.tempFile)) { fs_1.default.unlinkSync(this.tempFile); } } catch (ex) { console.warn(ex); } } } exports.default = MultipartFile;