uploading multiple files? #45
-
not example provided in the docs. how to achieve this? |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment
-
Hello, as explained in the provided example from the MultipartField documentation, the 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'
});
}); The above example is simply meant to be a "guide" and you should of course put in place other checks and cleanup mechanisms to ensure you have an efficient uploading endpoint. Hope that helps! |
Beta Was this translation helpful? Give feedback.
Hello, as explained in the provided example from the MultipartField documentation, the
Request.multipart()
method allows you to pass a handler which will get called with each multipart field attached from a multipart form. So If you wanted to upload multiple files, your code would look something like this:HTML Code Example