To upload files, in the past I expanded HttpServlet. I used it along with Commons-FileUpload .
I created a generic form-based download widget. This was to host downloads for different types of files (plain text and Base64). If you just need to download text files, you can combine the following two classes into one.
public class UploadFile extends Composite { @UiField FormPanel uploadForm; @UiField FileUpload fileUpload; @UiField Button uploadButton; interface Binder extends UiBinder<Widget, UploadFile> {} public UploadFile() { initWidget(GWT.<Binder> create(Binder.class).createAndBindUi(this)); fileUpload.setName("fileUpload"); uploadForm.setEncoding(FormPanel.ENCODING_MULTIPART); uploadForm.setMethod(FormPanel.METHOD_POST); uploadForm.addSubmitHandler(new SubmitHandler() { @Override public void onSubmit(SubmitEvent event) { if ("".equals(fileUpload.getFilename())) { Window.alert("No file selected"); event.cancel(); } } }); uploadButton.addClickHandler(new ClickHandler() { @Override public void onClick(ClickEvent event) { uploadForm.submit(); } }); } public HandlerRegistration addCompletedCallback( final AsyncCallback<String> callback) { return uploadForm.addSubmitCompleteHandler(new SubmitCompleteHandler() { @Override public void onSubmitComplete(SubmitCompleteEvent event) { callback.onSuccess(event.getResults()); } }); } }
The UiBinder part is pretty complicated.
<g:HTMLPanel> <g:HorizontalPanel> <g:FormPanel ui:field="uploadForm"> <g:FileUpload ui:field="fileUpload"></g:FileUpload> </g:FormPanel> <g:Button ui:field="uploadButton">Upload File</g:Button> </g:HorizontalPanel> </g:HTMLPanel>
Now you can extend this class for text files. Just make sure your web.xml serves for the HttpServlet in /textupload .
public class UploadFileAsText extends UploadFile { public UploadFileAsText() { uploadForm.setAction(GWT.getModuleBaseURL() + "textupload"); } }
The servlet for text files goes on the server side. It returns the contents of the downloaded file to the client. Be sure to install the jar for FileUpload from Apache Commons somewhere in your class path.
public class TextFileUploadServiceImpl extends HttpServlet { private static final long serialVersionUID = 1L; @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { if (! ServletFileUpload.isMultipartContent(request)) { response.sendError(HttpServletResponse.SC_BAD_REQUEST, "Not a multipart request"); return; } ServletFileUpload upload = new ServletFileUpload();
I canβt remember how I came across the <pre></pre> . You may need to filter tags on the client. The topic is also addressed here .
source share