Basic File upload in GWT
Here's the code from my app:
1) I created a class to accept http request:
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.fileupload.FileItemIterator;
import org.apache.commons.fileupload.FileItemStream;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
public class FileUpload extends HttpServlet{
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
ServletFileUpload upload = new ServletFileUpload();
try{
FileItemIterator iter = upload.getItemIterator(request);
while (iter.hasNext()) {
FileItemStream item = iter.next();
String name = item.getFieldName();
InputStream stream = item.openStream();
// Process the input stream
ByteArrayOutputStream out = new ByteArrayOutputStream();
int len;
byte[] buffer = new byte[8192];
while ((len = stream.read(buffer, 0, buffer.length)) != -1) {
out.write(buffer, 0, len);
}
int maxFileSize = 10*(1024*1024); //10 megs max
if (out.size() > maxFileSize) {
throw new RuntimeException("File is > than " + maxFileSize);
}
}
}
catch(Exception e){
throw new RuntimeException(e);
}
}
}
2) Then in my web.xml I've added these lines:
<servlet>
<servlet-name>fileUploaderServlet</servlet-name>
<servlet-class>com.testapp.server.FileUpload</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>fileUploaderServlet</servlet-name>
<url-pattern>/testapp/fileupload</url-pattern>
</servlet-mapping>
3) And for form.action did this:
form.setAction(GWT.getModuleBaseURL()+"fileupload");
How GWT fileupload works?
GWT's file upload makes use HTML's input element. The html input element is native html dom element which allows to select files from your system.
After selection you need to submit it to your server. This is done by the GWT's FormPanel.
In particular, FileUpload is only useful when used within a FormPanel, because the browser will only upload files using form submission.
Note:
1) You can read about how to code with formpanel and fileupload as answered here @ Basic File upload in GWT
2) If you are concerned with processing the file on client side and not pushing the file to server then you have limited options as mentioned here @ How to retrieve file from GWT FileUpload component?
GWT - Upload and get files uploaded with FileUpload
Solution:
I send files and all form data in a POST request to the servlet:
form.setAction(UPLOAD_ACTION_URL);
form.setEncoding(FormPanel.ENCODING_MULTIPART);
form.setMethod(FormPanel.METHOD_POST);
Then in my servlet, i get files path from the request:
DiskFileItemFactory factory = new DiskFileItemFactory();
ServletFileUpload upload = new ServletFileUpload(factory);
List<FileItem> items = upload.parseRequest(request);
Iterator<FileItem> iter = items.iterator();
while (iter.hasNext()) {
FileItem item = iter.next();
if (item.isFormField()) {
String fileName = new File(item.getName()).getName();
File uploadedFile = new File(fileName);
item.write(uploadedFile);
}
}
How to retrieve file from GWT FileUpload component?
I am guessing you want to allow user to upload file using GWT Fileupload widget and then do not wish to process it on server side. You want a byte array representation in client side.
Usual steps for File Processing
Browser -> File Upload Dialog -> Select File -> Submit Form with File to server -> Process File on Server -> Send back processed file to Client as response ( string ).
If you want to avoid the above steps and process the file in browser there is no way to do it in current javascript. Parallel technologies like Flash, Applet, Silverlight or Activex might help. The correct approach to be pursued in future would be using HTML5 file apis.
If you do not wish to use legacy technology like flash/applet then HTML5 apis on FileReader can be explored. However tradeoff is you need to check whether api is supported across browser.
HTML5 FileReader
FileReader includes four options for reading a file, asynchronously:
FileReader.readAsBinaryString(Blob|File) - The result property will contain the file/blob's data as a binary string.
FileReader.readAsText(Blob|File, opt_encoding) - The result property will contain the file/blob's data as a text string.
FileReader.readAsDataURL(Blob|File) - The result property will contain the file/blob's data encoded as a data URL.
FileReader.readAsArrayBuffer(Blob|File) - The result property will contain the file/blob's data as an ArrayBuffer object.
Example of GWT wrapper over these -
https://github.com/bradrydzewski/gwt-filesystem
Reference -
- http://www.html5rocks.com/en/tutorials/file/dndfiles/
- HTML5 File API read as text and binary
How to Upload a file 1 MB using GWT
You should use a form
instaed of gwtUpload
class. See this related topic:
Basic File upload in GWT
Itt will help.
How to upload only images in GWT fileUpload
HTML <input> has accept Attribute http://www.w3schools.com/tags/att_input_accept.asp
do like this on GWT
FileUpload upload=new FileUpload();
upload.getElement().setAttribute("accept", "image/*");
Related Topics
Consistency of Hashcode() on a Java String
How to Resolve Unable to Load Authentication Plugin 'Caching_Sha2_Password' Issue
Java 8 Streams Flatmap Method Example
Dealing with an Arraystoreexception
Serialization - Readobject Writeobject Overrides
How to Get a Reference Address
How to Convert Current Date into String in Java
What Is the Fastest Way to Compare Two Sets in Java
Static Allocation in Java - Heap, Stack and Permanent Generation
Managing Constructors with Many Parameters in Java
Why Does Sun.Misc.Unsafe Exist, and How Can It Be Used in the Real World
Is Java a Compiled or an Interpreted Programming Language
Mockito: Trying to Spy on Method Is Calling the Original Method