Open trasherdk opened 2 years ago
Slightly more verbose example:
app.put('/dp',(req,res)=>{
req.multipart(
{
limits: { files: 1, fileSize: 2 * 1024 * 1024 },
//@ts-ignore
headers: req.headers,
},
(field) => {
if (
field.mime_type != "image/jpeg" &&
field.mime_type != "image/png" &&
field.mime_type != "image/webp" &&
field.mime_type != "image/jiff" &&
field.mime_type != "image/svg"
) {
return res
.status(400)
.json({
message: "Wrong File Submitted, Imgaes Only",
status: false,
});
} [](url)
console.log(field.truncated);
console.log(field.file);
console.log(field.name);
console.log(field.encoding);
}
);
})
Source: https://github.com/kartikk221/hyper-express/discussions/86#discussioncomment-3113238
A even more verbose example, made from MultipartField documentation
HTML Code Example
<form action="https://example.com/files/upload" method="post" enctype="multipart/form-data">
<input type="text" name="text1" value="some text value">
<input type="text" name="text2" value="some text value">
<input type="file" name="file1">
<input type="file" name="file2">
<input type="file" name="file3">
<button type="submit">Upload</button>
</form>
Server Code Example
webserver.post('/files/upload', async (request, response) => {
// Wrap our multipart handler in a try-catch and create a "uploaded_files" array to store temporary paths of uploaded files
const uploaded_files = [];
try {
// Initiate multipart parsing
await request.multipart(async (field) => {
// Check if the current field is a file-type field
if (field.file) {
// Save the file temporarily to disk with a random UUID
const temp_path = '/path/to/tmp-folder/' + crypto.randomUUID();
await field.write(temp_path);
// Store the file's temporary path into the "uploaded_files" array so we can do stuff with it later
uploaded_files.push(temp_path);
}
});
} catch (error) {
// Send some error to the user if any occurs during multipart parsing
return response.status(500).json({
code: 'UPLOAD_ERROR',
message: 'There was a problem uploading your files, please try again'
});
}
// Return an error to the user if they did not upload any files
if (uploaded_files.length == 0)
return response.status(500).json({
code: 'NO_FILES_UPLOADED',
message: 'Please upload some files.'
});
// Do some stuff with the "uploaded_files" array here and be sure to clean up/delete any files you do not use
// Send a success response to the user
return response.json({
code: 'UPLOADED'
});
});
Source: https://github.com/kartikk221/hyper-express/discussions/45#discussioncomment-1907291
Source: https://github.com/kartikk221/hyper-express/discussions/92#discussioncomment-3147374