Skip to content

Instantly share code, notes, and snippets.

@artisonian
Last active May 17, 2020 12:56
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save artisonian/8297e5fe95f448ca98045f336bccf976 to your computer and use it in GitHub Desktop.
Save artisonian/8297e5fe95f448ca98045f336bccf976 to your computer and use it in GitHub Desktop.
import {
yellow,
cyan,
bold,
red
} from "https://deno.land/std@v0.31.0/fmt/colors.ts";
import { serve } from "https://deno.land/std@v0.31.0/http/mod.ts";
import {
MultipartReader,
FormFile
} from "https://deno.land/std@v0.31.0/mime/mod.ts";
import { decode } from "https://deno.land/std@v0.31.0/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