Java: Upload file and get back string (contents) of file
Hi I have GWT client with standard server-side Servlets.
- I can upload file from GWT client-side and read it's contents at server-side
- I can send it back to client as String
BUT
I have GWT FormPanel with action (myModule+"import"). FormPanel invokes POST from servlet. Browser then redirects me to myurl/import so I can see contents of uploaded file.
This is not what I wanted though. I'd simply like to have my String back. I added开发者_如何学C submitCompleteHandler to my FormPanel, but it doesn't log any results.
I noticed that servlets have method such setContentType
so I tried text/html, text/plain ... I don't know what should be there ...
To say it in one sentence, I want to send String back to client from servlet without having browser to redirect me somewhere else. Is it possible?
Since you are submitting a form you get your browser to change navigation. In order to make it work the way you want you have to send the file with ajax. For GWT there is the GWTUpload library that allows you to do that.
If the browser redirects you, it's because you gave a "target" to the FormPanel. By default, it submits within an hidden iframe (a.k.a "ajax upload").
As said in the javadoc, you have to setContentType("text/html")
in your servlet if you want onSubmitComplete
to be reliably called.
onSubmitComplete
's results is the returned HTML's body
innerHTML
so you have to be very careful when sending back values with <
or &
in them. The only reliable way to get them back is to escape them on the server-side, and unescape them on the client-side. You can either use your own escaping mechanism, or you can use <
and &
. In the latter case, to unescape on the client-side, you'd either use String#replace, or create an HTML element, set it's innerHTML with the string you got back, and then get its innerText:
public String htmlUnescape(String htmlEscaped) {
Element tmp = Document.get().createDivElement();
tmp.setInnerHTML(htmlEscaped);
return tmp.getInnerText();
}
On the server-side, you'd use:
escaped = content.replace("&", "&").replace("<", "<")
(order matters here if you don't want <
s to become &lt;
; also, replacing <
and &
is enough, >
and "
won't cause any issue here)
In your case however, make sure first that the file's content is "text" and not "binary", as it wouldn't make sense to return it as String could cause issues depending on how you use the value on the client side.
精彩评论