| import * as fs from 'fs'; | |
| import * as path from 'path'; | |
| import { Context } from 'koa'; | |
| const UPLOAD_DIR = path.join(__dirname, '../../uploads'); | |
| export const getFileNameList = async (ctx: Context) => { | |
| try { | |
| const files = fs.readdirSync(UPLOAD_DIR); | |
| ctx.body = { files }; | |
| } catch (error: any) { | |
| ctx.status = 500; | |
| ctx.body = { error: error.message }; | |
| } | |
| }; | |
| export const uploadFile = async (ctx: Context) => { | |
| try { | |
| if (!ctx.request.body || !ctx.request.header['content-disposition']) { | |
| ctx.status = 400; | |
| ctx.body = { error: 'No file or file name uploaded' }; | |
| return; | |
| } | |
| const fileBuffer = ctx.request.body; | |
| const contentDisposition = ctx.request.header['content-disposition']; | |
| const fileNameMatch = contentDisposition.match(/filename=(.+)/); | |
| if (!fileNameMatch) { | |
| ctx.status = 400; | |
| ctx.body = { error: 'File name not found in Content-Disposition header' }; | |
| return; | |
| } | |
| const fileName = fileNameMatch[1]; | |
| const targetPath = path.join(UPLOAD_DIR, fileName); | |
| fs.writeFileSync(targetPath, fileBuffer); | |
| ctx.body = { message: 'File uploaded successfully' }; | |
| } catch (error: any) { | |
| ctx.status = 500; | |
| ctx.body = { error: error.message }; | |
| } | |
| }; | |
| export const getFile = async (ctx: Context) => { | |
| try { | |
| const fileName = ctx.params.fileName; | |
| const filePath = path.join(UPLOAD_DIR, fileName); | |
| if (!fs.existsSync(filePath)) { | |
| ctx.status = 404; | |
| ctx.body = { error: 'File not found' }; | |
| return; | |
| } | |
| ctx.attachment(fileName); | |
| ctx.body = fs.createReadStream(filePath); | |
| } catch (error: any) { | |
| ctx.status = 500; | |
| ctx.body = { error: error.message }; | |
| } | |
| }; | |
| export const deleteFile = async (ctx: Context) => { | |
| try { | |
| const { fileName } = ctx.request.body; | |
| if (!fileName) { | |
| ctx.status = 400; | |
| ctx.body = { error: 'File name is required' }; | |
| return; | |
| } | |
| const filePath = path.join(UPLOAD_DIR, fileName); | |
| if (!fs.existsSync(filePath)) { | |
| ctx.status = 404; | |
| ctx.body = { error: 'File not found' }; | |
| return; | |
| } | |
| fs.unlinkSync(filePath); | |
| ctx.body = { message: 'File deleted successfully' }; | |
| } catch (error: any) { | |
| ctx.status = 500; | |
| ctx.body = { error: error.message }; | |
| } | |
| }; | |