cxos-node-frame
Version:
适用于中小型企业项目快速全栈开发框架
84 lines (79 loc) • 3.1 kB
JavaScript
const fs = require('fs')
const path = require('path')
const send = require("koa-send");
const uuidv4 = require('uuid').v4
module.exports = (app) => {
const BusinessError = require('../base/error')()
const RestAPI = require("../base/restapi")()
const FileService = require('../service/fileService')(app)
class FileController {
// 服务器静态资源目录
static static = 'static'
/**
* 返回服务器文件流
* @param ctx
* @param next
* @returns {Promise<void>}
*/
async get(ctx, next) {
if (!ctx.query || !ctx.query.src) {
throw new BusinessError(1000, '非法src参数!')
}
const fileDir = app.file['dir']
const filePath = fileDir + ctx.query.src
const size = fs.statSync(filePath).size
const createReadStream = await fs.createReadStream(filePath)
const ext = filePath.substring(filePath.lastIndexOf('.'))
ctx.set('Content-disposition', 'attachment; filename=' + uuidv4() + ext)
ctx.set('Content-type', 'application/force-download')
ctx.set('Content-Length', size)
ctx.body = createReadStream
}
/**
* 客户端下载需要的存放在服务端下的static资源文件
* @param ctx
* @param next
* @returns {Promise<void>}
*/
async load(ctx, next) {
const root = process.cwd() + new FileService().getServerSplit() + FileController.static
if (!ctx.query || !ctx.query.src) {
throw new BusinessError(1000, '非法src参数!')
}
const filePath = root + '/' + ctx.query.src
const fileName = filePath.substring(filePath.lastIndexOf(new FileService().getServerSplit() + 1))
const Size = fs.statSync(filePath).size
const createReadStream = await fs.createReadStream(filePath)
ctx.set('Content-disposition', 'attachment; filename=' + fileName)
ctx.set('Content-type', 'application/force-download')
ctx.set('Content-Length', Size)
ctx.body = createReadStream
}
/**
* 文件上传
* @param ctx
* @param next
* @returns {Promise<void>}
*/
async upload(ctx, next){
const result = await new FileService().upload(ctx)
ctx.body = JSON.stringify(new RestAPI(result))
}
/**
* 下载服务器文件
* @param ctx
* @param next
* @returns {Promise<void>}
*/
async download(ctx, next){
if (!ctx.query || !ctx.query.src) {
throw new BusinessError(1000, '非法src参数!')
}
const filePath = ctx.query.src
ctx.attachment(filePath)
await send(ctx, filePath, {root: fileDir})
}
}
return FileController
}