Skip to content

Instantly share code, notes, and snippets.

@artisonian
Last active May 17, 2020
Embed
What would you like to do?
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