Handling file uploads #
Diego uses the FileUpload abstraction to work with binary content sent from the client to your application.
When using the Express-style routing, you can access file uploads using the Context#getFileUpload() or Context#fileUploads() methods. When using Controllers, simply use the @Attachment annotation with your FileUpload parameter:
// Express-style
app.post("/upload", ctx -> {
final FileUpload upload = ctx.getFileUpload("photo");
upload.copyTo(Paths.get("./profile-pics"));
});
// Controller action
@POST
public Result upload(@Attachment FileUpload photo) {
photo.copyTo(Paths.get("./profile-pics"));
}
Important: Uploads are not automatically written to disk. This allows you to inspect the properties of the uploaded content before committing it. Use the FileUpload#copyTo() method to save the uploaded content. The Path supplied to this method can be a directory or your own preferred file name.
Alternatively, you can get more fine grained control over the uploaded data by leveraging the getInputStream() and getTemporaryFileName() methods.
Configuration #
You can configure certain aspects of the request body handler using the diego.http section of your application.conf file:
# Set the max file size for uploads
diego.http.maxFileSize = "5MB"
# Set the max request body size
diego.http.maxBodySize = "10MB"
The sizes are specified using a byte format.
Reminder: Only multipart/form-data requests can transfer files.
Next: Rendering templates