File Upload
Upload files with multipart/form-data in a form
In a web application, the standard upload file is a form encoded with multipart/form-data, which allows mixed form data in the form of file attachments. Note that for the HTTP method of such a form, it must be submitted by POST
1. Open the routes file and add POST /upload controllers.UserControl.upload()
2. In UserControl.java, add
public static Result upload(){
MultipartFormData body=request().body().asMultipartFormData();
FilePart picture=body.getFile("picture");
if(picture!=null){
String filename=picture.getFilename();
String contentType=picture.getContentType();
File file=picture.getFile();
System.out.println("filename:"+filename+",contentType:"+contentType);
return ok("File load");
}else{
flash("error","Miss file");
return redirect(routes.Application.index());
}
}
3. Open form.scala.html and join
<form action="/upload" method="post" enctype="multipart/form-data">
<input type="file" name="picture">
<p>
<input type="submit">
</p>
</form>
Direct file upload
Another way to upload files is to use ajax to upload files asynchronously from a form. In this case, the requested body will not be encoded as Multipart/form-data, and only contains the content of the plain text file.
public static Result upload() {
File file = request().body().asRaw().asFile();
return ok("File uploaded");
}