Deno上传文件

醉酒当歌 提交于 2020-08-18 06:51:35

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

<body>
<form id="yourFormId" enctype="multipart/form-data" action="/uploadAction" method="post">
    <input type="file" name="file1" multiple><br>
    <input type="submit" value="Submit">
  </form>
</body> 

#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 })  

 

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!