Mentawai makes it very easy to upload a file, abstracting any complexity away from the developer.
Setting up the file field in the HTML form:
<mtw:form action="HelloFileUpload.mtw" method="post" enctype="multipart/form-data"> Enter an username: <mtw:input name="username" size="25" /><br/> Enter filename: <input name="theFile" type="file" /><br/> <input type="submit" value="Enviar"> </mtw:form>
Setting up the file upload for an action in the application manager:
action("/File", FileAction.class, "upload") .fileUpload() .on(SUCCESS, redir(mainAction));
The fileUpload() method has other options that you can use to fine-tune the upload process:
fileUpload(int maxInMemorySize); // <=== will write to disk once the limit is reached... fileUpload(int maxInMemorySize, int maxSizeToThrowError); // <=== so the user does not try to upload a 10Gb file... fileUpload(int maxInMemorySize, String tempDirInsideWebInf); // <=== directory where temp files will be stored... fileUpload(int maxInMemorySize, int maxSizeToThrowError, String tempDirInsideWebInf);
Getting the file inside the action:
public String upload() throws IOException { FileUpload fileUpload = (FileUpload) input.getValue("theFile"); File file = getDestinationFile(fileUpload.getOriginalFilename()); // choose somehow the destination filename here FileOutputStream fos = new FileOutputStream(file); // the destination InputStream is = fileUpload.getInpuStream(); // the upload input stream byte[] data = new byte[4096]; int read; while((read = is.read(data)) != -1) { fos.write(data, 0, read); } is.close(); fos.close(); fileUpload.deleteTempFile(); // get rid of the temp file if present... (optional because it will happen eventually) return SUCCESS; }
More methods you can use from the FileUpload object:
public void deleteTempFile(); public byte[] toByteArray(); public String getContentType(); public String getFieldName(); public String getOriginalFilename(); public long getSize(); public String asString(); public String asString(String encoding); public boolean isInMemory(); public InputStream getInpuStream(); public FileItem getFileItem(); // the underlying Apache Commons FileItem object