|
@@ -265,3 +265,72 @@ router
|
|
);
|
|
);
|
|
```
|
|
```
|
|
|
|
|
|
|
|
+**实际开发时,在上传文件时会指定文件最终存储的目录下,此时除了在请求体中通过file指定要上传的文件之外,在添加一个参数folder 用以指定上传后文件的存储位置。**
|
|
|
|
+
|
|
|
|
+
|
|
|
|
+
|
|
|
|
+```js
|
|
|
|
+import Router from '@koa/router';
|
|
|
|
+import { koaBody } from 'koa-body';
|
|
|
|
+import { copyFile, rm, access, mkdir } from 'node:fs/promises';
|
|
|
|
+import { UPLOAD_DIR, STATIC } from '../app.config.mjs';
|
|
|
|
+const router = new Router();
|
|
|
|
+// 通过router实例的一些方法 比如 get、post等去定义 对应请求方法的路由
|
|
|
|
+router
|
|
|
|
+ .put(
|
|
|
|
+ '/upload',
|
|
|
|
+ koaBody({
|
|
|
|
+ multipart: true,
|
|
|
|
+ formidable: {
|
|
|
|
+ keepExtensions: true,
|
|
|
|
+ uploadDir: UPLOAD_DIR, // 设置上传文件的最终位置
|
|
|
|
+ },
|
|
|
|
+ onError(err, ctx) {
|
|
|
|
+ ctx.body = {
|
|
|
|
+ code: 1,
|
|
|
|
+ msg: err,
|
|
|
|
+ };
|
|
|
|
+ },
|
|
|
|
+ }),
|
|
|
|
+ async (ctx) => {
|
|
|
|
+ let filename = ctx.request.files.file.newFilename;
|
|
|
|
+ let srcFile = `./${UPLOAD_DIR}/${filename}`;
|
|
|
|
+ let destFile = srcFile;
|
|
|
|
+ // 获取 请求体 中 除了file文件之外的其他数据
|
|
|
|
+ const { folder } = ctx.request.body;
|
|
|
|
+ // 如果用户在上传文件时 指定了目标文件夹
|
|
|
|
+ if (folder) {
|
|
|
|
+ // 1 将默认上传位置的文件 拷贝到 目标的文件夹下
|
|
|
|
+ destFile = `./${UPLOAD_DIR}/${folder}/${filename}`;
|
|
|
|
+ try {
|
|
|
|
+ // 先确保destFile的文件夹都真实存在
|
|
|
|
+ let isExist = await access(`./${UPLOAD_DIR}/${folder}`).catch(
|
|
|
|
+ () => false
|
|
|
|
+ );
|
|
|
|
+ // isExist 就是 undefined 或者 false
|
|
|
|
+ if (isExist == false) {
|
|
|
|
+ // 如果不存在 就创建
|
|
|
|
+ await mkdir(`./${UPLOAD_DIR}/${folder}`, { recursive: true });
|
|
|
|
+ }
|
|
|
|
+
|
|
|
|
+ await copyFile(srcFile, destFile);
|
|
|
|
+ // 2 成功后 删除默认位置的文件
|
|
|
|
+ await rm(srcFile);
|
|
|
|
+ } catch (error) {
|
|
|
|
+ console.error(error);
|
|
|
|
+ }
|
|
|
|
+ }
|
|
|
|
+ // 给客户端响应数据
|
|
|
|
+ ctx.body = {
|
|
|
|
+ code: 0,
|
|
|
|
+ data: {
|
|
|
|
+ path: `${UPLOAD_DIR.replace(STATIC, '')}/${folder}/${filename}`,
|
|
|
|
+ filename,
|
|
|
|
+ },
|
|
|
|
+ msg: '上传成功',
|
|
|
|
+ };
|
|
|
|
+ }
|
|
|
|
+ );
|
|
|
|
+export default router;
|
|
|
|
+```
|
|
|
|
+
|