You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
82 lines
2.8 KiB
82 lines
2.8 KiB
import path from "path"
|
|
import { gSuccess, gFail, uploadDir, uploadPath } from "@/util"
|
|
import { dateTimeFormat } from "@/util/util"
|
|
const fs = require("fs")
|
|
const multiparty = require("multiparty")
|
|
const FileType = require("file-type")
|
|
|
|
function saveFile(file) {
|
|
return new Promise(async (resolve, reject) => {
|
|
const filename = file.originalFilename
|
|
const uploadedPath = file.path
|
|
const filetype = await FileType.fromFile(uploadedPath)
|
|
const _file = path.parse(filename)
|
|
if (filetype && (filetype.ext == "jpg" || filetype.ext == "png")) {
|
|
let _name =
|
|
_file.name + "_" + dateTimeFormat(new Date(), "yyyy_MM_dd") + "_" + new Date().getTime() + _file.ext
|
|
const dstPath = path.resolve(uploadDir, _name)
|
|
fs.rename(uploadedPath, dstPath, function (err) {
|
|
if (err) {
|
|
console.log("rename error: " + err)
|
|
reject()
|
|
} else {
|
|
resolve(dstPath)
|
|
}
|
|
})
|
|
} else {
|
|
fs.unlinkSync(uploadedPath)
|
|
reject(new Error(filename + "文件不是图片"))
|
|
}
|
|
})
|
|
}
|
|
|
|
export default function (req, h) {
|
|
const form = new multiparty.Form({
|
|
uploadDir: uploadDir, //路径需要对应自己的项目更改
|
|
/*设置文件保存路径 */
|
|
encoding: "utf-8",
|
|
/*编码设置 */
|
|
maxFilesSize: 20000 * 1024 * 1024,
|
|
/*设置文件最大值 20MB */
|
|
keepExtensions: true,
|
|
/*保留后缀*/
|
|
})
|
|
return new Promise(async (resolve, reject) => {
|
|
form.on("part", function (part) {
|
|
console.log(part.filename)
|
|
})
|
|
form.on("progress", function (bytesReceived, bytesExpected) {
|
|
if (bytesExpected === null) {
|
|
return
|
|
}
|
|
|
|
var percentComplete = (bytesReceived / bytesExpected) * 100
|
|
console.log("the form is " + Math.floor(percentComplete) + "%" + " complete")
|
|
})
|
|
form.parse(req.payload, async function (err, fields, files) {
|
|
// console.log(err, fields, files);
|
|
|
|
if (err) {
|
|
resolve(err.message)
|
|
return
|
|
}
|
|
const errList = []
|
|
const fileList = []
|
|
for (let i = 0; i < files.file.length; i++) {
|
|
const file = files.file[i]
|
|
try {
|
|
const dstPath = await saveFile(file)
|
|
fileList.push(dstPath)
|
|
} catch (error) {
|
|
errList.push(error.message)
|
|
}
|
|
}
|
|
if (errList.length) {
|
|
resolve(gFail(null, errList.join("\n")))
|
|
return
|
|
}
|
|
// resolve(h.view("views/upload.ejs"));
|
|
resolve([...new Set(fileList)])
|
|
})
|
|
})
|
|
}
|
|
|