3rd Lib
- axios
- fastify
- fastify-multipart
| const fastify = require('fastify')() | |
| const fs = require('fs') | |
| const util = require('util') | |
| const path = require('path') | |
| const { pipeline } = require('stream') | |
| const pump = util.promisify(pipeline) | |
| fastify.register(require('fastify-multipart')) | |
| fastify.post('/', async function (req, reply) { | |
| // process a single file | |
| // also, consider that if you allow to upload multiple files | |
| // you must consume all files otherwise the promise will never fulfill | |
| const data = await req.file() | |
| data.file // stream | |
| data.fields // other parsed parts | |
| data.fieldname | |
| data.filename | |
| data.encoding | |
| data.mimetype | |
| // to accumulate the file in memory! Be careful! | |
| // | |
| // await data.toBuffer() // Buffer | |
| // | |
| // or | |
| await pump(data.file, fs.createWriteStream(data.filename)) | |
| // be careful of permission issues on disk and not overwrite | |
| // sensitive files that could cause security risks | |
| // also, consider that if the file stream is not consumed, the promise will never fulfill | |
| reply.send() | |
| }) | |
| fastify.listen(3000, err => { | |
| if (err) throw err | |
| console.log(`server listening on ${fastify.server.address().port}`) | |
| }) |
| <input type="file" onChange={onChange} accept ="image/*"/> | |
| <script> | |
| const onChange = (e) => { | |
| let url = "http://localhost:3000/"; | |
| let file = e.target.files[0]; | |
| uploadFile(url, file); | |
| }; | |
| const uploadFile = (url, file) => { | |
| let formData = new FormData(); | |
| formData.append("file", file); | |
| axios.post(url, formData, { | |
| headers: { | |
| "Content-Type": "multipart/form-data", | |
| }, | |
| }).then((response) => { | |
| fnSuccess(response); | |
| }).catch((error) => { | |
| fnFail(error); | |
| }); | |
| }; | |
| const fnSuccess = (response) => { | |
| //Add success handling | |
| }; | |
| const fnFail = (error) => { | |
| //Add failed handling | |
| }; | |
| </script> |