Deno上传文件

Deno上传文件

视频讲解 https://www.bilibili.com/video/BV1BT4y1E7Nh/?p=6

我们一起来完成以下步骤:

  1. 沿用之前的工程代码
  2. 创建上传页面和响应的controller
  3. 添加上传文件功能
  4. 测试

controllers/controller.ts


const { cwd } = Deno;

class Controller {
    static async getData(ctx: any){
        //cwd获取当前工程目录 
        //注意 ' !== `
        ctx.render(`${cwd()}/views/index.ejs`,{
            title:"Testing",
            data:{name:"deepincoding"}
        }); 
    }
    static async uploadPage(ctx: any){
        ctx.render(`${cwd()}/views/upload-page.ejs`);
    }

    static async uploadAction(ctx: any){
        //我们这里不返回页面,而是返回上传文件的信息
        ctx.response.body = ctx.uploadedFiles;
    }
    
}

export default Controller;

routers/index.ts


import { Router } from "https://deno.land/x/oak/mod.ts";
import Controller from "../controllers/Controller.ts";
import { upload } from "https://deno.land/x/upload_middleware_for_oak_framework/mod.ts";


const router = new Router();

router.get("/",Controller.getData);

router.get("/uploadPage",Controller.uploadPage);

router.post("/uploadAction", upload('uploads', ['jpg','png'], 20000000, 10000000, true, false, true),Controller.uploadAction);

export default router;

views/upload-page.ejs




main.ts



import { Application } from "https://deno.land/x/oak/mod.ts"
import {viewEngine,engineFactory,adapterFactory} from "https://deno.land/x/view_engine/mod.ts";
import router from "./routers/index.ts";

const ejsEngine = engineFactory.getEjsEngine();
const oakAdapter = adapterFactory.getOakAdapter();

const app = new Application();
app.use(viewEngine(oakAdapter,ejsEngine));
app.use(router.routes());
app.use(router.allowedMethods());

await app.listen({port: 8000 })

你可能感兴趣的:(deno)