Deno로 파일 업로드
17304 단어 denotypescriptjavascripttutorial
먼저 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 });
여기에서 무슨 일이 일어나고 있습니까?
이제 앱을 실행해 보겠습니다. 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은 매우 쉽고 재미있고 빠릅니다! 즐거운 코딩!
Reference
이 문제에 관하여(Deno로 파일 업로드), 우리는 이곳에서 더 많은 자료를 발견하고 링크를 클릭하여 보았다 https://dev.to/scottlepp/uploading-files-with-deno-1m00텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
우수한 개발자 콘텐츠 발견에 전념 (Collection and Share based on the CC Protocol.)