Deno로 파일 업로드

여기에서는 Deno를 사용하여 파일을 업로드하는 방법에 대한 빠른 자습서를 보여 드리겠습니다. 파일은 브라우저에서 볼 수 있는 기능과 함께 디스크에 저장됩니다.

먼저 Deno 을 설치합니다.

이제 앱을 제공할 파일을 추가합니다. 앱을 포함할 프로젝트 폴더를 만든 다음 server라는 하위 폴더를 추가합니다. 우리는 또한 그것을 테스트할 클라이언트를 생성할 것입니다. 서버와 클라이언트 폴더가 있으면 프로젝트를 구성하는 데 도움이 됩니다.

server.ts 파일을 서버 폴더에 추가하십시오. 그리고 코드를 추가하세요:

import { Application, send } from "https://deno.land/x/oak/mod.ts";
import { FormFile, multiParser } from 'https://deno.land/x/[email protected]/mod.ts'
import { oakCors } from "https://deno.land/x/cors/mod.ts";

const app = new Application();

app.use(
  oakCors({
    origin: true
  }),
);

app.use(async (ctx) => {
  const path = ctx.request.url.pathname;
  if (path === '/upload') {
    const form = await multiParser(ctx.request.serverRequest)
    if (form) {
      const image: FormFile = form.files.image as FormFile
      try {
        await Deno.writeFile(`images/${image.filename}`, image.content);
      } catch (e) {
        console.error(e)
      }
    }
    ctx.response.body = '{"status": "ok"}';
  }

  if (ctx.request.method === 'GET' && path.startsWith('/images')) {
    await send(ctx, ctx.request.url.pathname, {
      root: `${Deno.cwd()}`
   });
  }
});

app.listen({ port: 8082 });


여기에서 무슨 일이 일어나고 있습니까?
  • 맨 위에서 종속성을 가져옵니다.
  • 그런 다음 앱을 만든 다음 app.use를 사용하여 미들웨어를 등록합니다.
  • OakCors는 모든 클라이언트가 서버를 호출할 수 있도록 허용합니다(데모의 경우 확인).
  • 두 번째 app.use 블록에서/upload 및/images 경로를 정의합니다. 클라이언트에서/upload에 게시하고/images를 사용하여 이미지를 볼 수 있습니다.
  • /upload는 게시된 양식에서 파일을 가져와 폴더에 씁니다
  • .

    이제 앱을 실행해 보겠습니다. http 호출에 대해 allow-net에 대한 권한을 설정하고 이미지 쓰기 및 읽기에 대해 allow-write/allow-read에 대한 권한을 설정해야 합니다. 그런 다음 deno에게 server.ts 파일을 실행하도록 지시합니다.

    deno run \
    --allow-net \
    --allow-write=./images \
    --allow-read=./,./images \
    ./server/server.ts
    


    이제 클라이언트를 추가해 보겠습니다. 클라이언트 폴더를 추가하고 다음을 사용하여 index.html 파일을 만듭니다.

    <html>
      <head>
        <script src="./index.js"></script>
      </head>
      <body>
        <input type="file" name="file" id="imgfile" onchange="loadImage()">
        <input type='button' id='btnLoad' value='Upload' onclick="upload()" />
        <canvas id="canvas"></canvas>
      </body>
    </html>
    


    이제 다음을 사용하여 index.js 파일을 추가하십시오.

    async function post(canvas, name) {
      const ts = new Date().getTime();
      canvas.toBlob(async function(blob) {
        const formData = new FormData();
        formData.append('image', blob, name);
        const res = await fetch('http://localhost:8082/upload', {
          mode: 'no-cors',
          method: 'POST',
          body: formData
        });
      });
    }
    
    function loadImage() {
      let img;
    
      const input = document.getElementById('imgfile');
      if (!input.files[0]) {
          write("Please select a file before clicking 'Load'");
          return;
      }
    
      const file = input.files[0];
      const fr = new FileReader();
      fr.onload = createImage;
      fr.readAsDataURL(file);
    
      function createImage() {
          img = new Image();
          img.onload = imageLoaded;
          img.src = fr.result;
      }
    
      function imageLoaded() {
          const canvas = document.getElementById("canvas")
          canvas.width = img.width;
          canvas.height = img.height;
          const ctx = canvas.getContext("2d");
          ctx.drawImage(img,0,0);
      }
    
    }
    
    async function upload() {
      const canvas = document.getElementById("canvas")
      const input = document.getElementById('imgfile');
      await post(canvas, input.files[0].name);
      write('File uploaded')
    }
    
    function write(msg) {
      const p = document.createElement('p');
      p.innerHTML = msg;
      document.body.appendChild(p);
    }
    


    이제 index.html 파일을 열고 이미지를 선택하고 업로드하십시오! Deno와 함께 이 페이지를 제공할 수 있지만 이 데모에서는 실제로 필요하지 않습니다.

    업로드한 이미지를 보려면 다음으로 이동하십시오. localhost:8082/images/[yourimagename]

    여기 전체 GitHub Project

    보시다시피 Deno은 매우 쉽고 재미있고 빠릅니다! 즐거운 코딩!

    좋은 웹페이지 즐겨찾기