Last active
May 17, 2020 12:56
-
-
Save artisonian/8297e5fe95f448ca98045f336bccf976 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { | |
yellow, | |
cyan, | |
bold, | |
red | |
} from "https://deno.land/[email protected]/fmt/colors.ts"; | |
import { serve } from "https://deno.land/[email protected]/http/mod.ts"; | |
import { | |
MultipartReader, | |
FormFile | |
} from "https://deno.land/[email protected]/mime/mod.ts"; | |
import { decode } from "https://deno.land/[email protected]/strings/mod.ts"; | |
const s = serve({ port: 1447 }); | |
console.log(bold("Listening on"), yellow("http://localhost:1447/")); | |
const html = `<!DOCTYPE html> | |
<html> | |
<head> | |
<title>Multipart Reader Example</title> | |
</head> | |
<body> | |
<form method="POST" action="/upload" enctype="multipart/form-data"> | |
<label for="attachment">Attach file:</label> | |
<input name="attachment" type="file" /> | |
<button type="submit">Upload</button> | |
</form> | |
</body> | |
`; | |
for await (const req of s) { | |
if (req.url === "/upload" && req.method !== "POST") { | |
req.respond({ | |
status: 405, | |
body: "405 Method Not Allowed" | |
}); | |
} else if (req.url === "/upload") { | |
try { | |
const contentType = req.headers.get("content-type"); | |
const boundary = contentType.match(/boundary=([^\s]+)/)[1]; | |
const reader = new MultipartReader(req.body, boundary); | |
const form = await reader.readForm(1024 * 1024); // 1MB | |
console.log(form); | |
const attachment = form.attachment as FormFile; | |
if (attachment.content) { | |
console.log(cyan("content"), decode(attachment.content)); | |
} else if (attachment.tempfile) { | |
console.log( | |
cyan("content"), | |
decode(await Deno.readFile(attachment.tempfile)) | |
); | |
} | |
const headers = new Headers(); | |
headers.set("Location", "/"); | |
req.respond({ | |
status: 302, | |
headers | |
}); | |
} catch (e) { | |
console.error(red(e.message)); | |
console.error(e.stack); | |
req.respond({ | |
status: 500, | |
body: "500 Internal Server Error" | |
}); | |
} | |
} else { | |
req.respond({ body: html }); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment