config.default.js 添加
config. multipart = {
mode : 'file'
} ;
config. static = {
prefix : '/static' ,
dir : path. join ( appInfo. baseDir, 'app/public' ) ,
dynamic : true ,
preload : false ,
maxAge : 31536000 ,
buffer : true ,
} ;
上述配置参照博客
https://www.jianshu.com/p/7e23f1c69279
Controller
const Controller = require ( 'egg' ) . Controller;
class uploadFileController extends Controller {
async uploadImage ( ) {
const { ctx } = this ;
const files = ctx. request. files;
console. log ( files)
const result = await ctx. service. uploadFileService. saveImages ( files) ;
ctx. body = result;
}
}
module. exports = uploadFileController;
Service 层
const Service = require ( 'egg' ) . Service;
const fs = require ( 'fs' ) ;
const path = require ( 'path' ) ;
const crypto = require ( 'crypto' ) ;
class uploadFileService extends Service {
async saveImages ( files ) {
const ctx = this . ctx;
const uploadDir = 'app/public/' ;
try {
if ( files. length !== 1 ) {
return { success : false , message : 'Only one image can be uploaded at a time' } ;
}
const file = files[ 0 ] ;
const fileName = file. filename;
const hash = crypto. createHash ( 'md5' ) . update ( fileName) . digest ( 'hex' ) ;
const timestamp = Date. now ( ) ;
const newFileName = ` ${ hash} _ ${ timestamp} ${ path. extname ( fileName) } ` ;
const filePath = path. join ( uploadDir, newFileName) ;
console. log ( newFileName, "====================" ) ;
const writeStream = fs. createWriteStream ( filePath) ;
const readStream = fs. createReadStream ( file. filepath) ;
readStream. pipe ( writeStream) ;
return { success : true , message : ` http://127.0.0.1:7001/static/ ${ newFileName} ` } ;
} catch ( err) {
return { success : false , message : 'Failed to upload image' } ;
}
}
}
module. exports = uploadFileService;