Skip to content

Instantly share code, notes, and snippets.

@zoutepopcorn
Last active February 17, 2023 13:41
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save zoutepopcorn/96b287298084d039aed650cdfdf170a1 to your computer and use it in GitHub Desktop.
Save zoutepopcorn/96b287298084d039aed650cdfdf170a1 to your computer and use it in GitHub Desktop.
<html>
<body>
<h1>cors test</h1>
<script>
const tester = async () => {
const out = await fetch("http://localhost:7777/");
const text = await out.text()
console.log(text);
}
tester();
</script>
</body>
</html>
import fastify from 'fastify';
import staticServer from '@fastify/static';
import cors from '@fastify/cors';
import { resolve } from 'path';
const server = fastify()
server.register(cors, {origin: "*"});
server.register(staticServer, {
root: resolve('public')
})
// prefix: '/front',
server.listen({port: 7777, host: "0.0.0.0"}, (err, address) => {
if (err) {
console.error(err)
process.exit(1)
}
console.log(`Server listening at ${address}`)
})
<html>
<body>
<body>
<div class="container">
<h1>Multipart File Upload</h1>
<form id="form" enctype="multipart/form-data">
<div class="input-group">
<label for="files">Select files</label>
<input id="file" type="file" multiple />
</div>
<button class="submit-btn" type="submit">Upload</button>
</form>
</div>
<script>
const form = document.getElementById("form");
const inputFile = document.getElementById("file");
const formData = new FormData();
const handleSubmit = (event) => {
event.preventDefault();
for (const file of inputFile.files) {
formData.append("files", file);
}
fetch("http://localhost:9090/upload", {
method: "post",
body: formData,
}).catch((error) => {
("Something went wrong!", error)
});
};
form.addEventListener("submit", handleSubmit);
</script>
</body>
</html>
import fastify from "fastify";
import cors from '@fastify/cors';
import fs from 'fs';
import pump from 'pump';
import fastifyMultipart from "@fastify/multipart";
const server = fastify();
server.register(cors, {origin: "*"});
server.register(fastifyMultipart);
server.post('/upload', async (req, reply) => {
const files = await req.files();
console.log("UPLOAD")
console.log(files.length);
for await (const part of files) {
req.log.info('storing %s', part.filename);
const storedFile = fs.createWriteStream(`./output/${part.filename}`);
await pump(part.file, storedFile);
}
return { upload: 'completed' }
});
server.listen({port: 9090}, (err, address) => {
if (err) {
console.error(err)
process.exit(1)
}
console.log(`Server listening at ${address}`)
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment