Is there a multipart POST library out there that achieve the same effect of doing a POST from a html form? for example - upload a file programmingly in Java versus upload the file using a html form. And on the server side, it just blindly expect the request from client side to be a multipart POST request and parse out the data as appropriate.
Has anyone tried this?
specifically, I am trying to see if I can simulate the following with Java
The user creates a blob by submitting an HTML form that includes one or more file input fields. Your app sets blobstoreService.createUploadUrl() as the destination (action) of this form, passing the function a URL path of a handler in your app. When the user submits the form, the user's browser uploads the specified files directly to the Blobstore. The Blobstore rewrites the user's request and stores the uploaded file data, replacing the uploaded file data with one or more corresponding blob keys, then passes the rewritten request to the handler at the URL path you provided to blobstoreService.createUploadUrl(). This handler can do additional processing based on the blob key. Finally, the handler must return a headers-only, redirect response (301, 302, or 303), typically a browser redirect to another page indicating the status of the blob upload.
Set blobstoreService.createUploadUrl as the form action, passing the application path to load when the POST of the form is completed.
<body>
<form action="<%= blobstoreService.createUploadUrl("/upload") %>" method="post" enctype="multipart/form-data">
<input type="file" name="myFile">
<input type="submit" value="Submit">
</form>
</body>
Note that this is how the upload form would look if it were created as a JSP.
The form must include a file upload field, and the form's enctype must be set to multipart/form-data. When the user submits the form, the POST is handled by the Blobstore API, which creates the blob. The API also creates an info record for the blob and stores the record in the datastore, and passes the rewritten request to your app on the given path as a blob key.
You don't need a library; this is possible with the stock Java classes (example).
On the server side you will implement a Java Servlet solution that makes parsing HTTP request parameters very simple.
A complete and de facto standard HTTP implementation (included for example in the Android platform) you will find at Apache httpcomponent
Related
Can I send a file as multipart by XMLHttpRequest to a servlet?
I am making a form and submitting it as multipart, but somehow I am not getting a response for successfully uploading it. I do not want the page to be refreshed, so it has to take place by Ajax.
That's only possible with the XHR FormData API (previously known being part of as "XHR2" or "XHR Level 2", currently known as "XHR Advanced Features").
Given this HTML,
<input type="file" id="myFileField" name="myFile" />
you can upload it as below:
var formData = new FormData();
formData.append("myFile", document.getElementById("myFileField").files[0]);
var xhr = new XMLHttpRequest();
xhr.open("POST", "myServletUrl");
xhr.send(formData);
XHR will take care about proper headers and request body encoding and the file will in this example be available on the server side as form-data part with the name myFile.
You need to keep in mind that FormData API is not supported in older browsers. At caniuse.com you can see that it's currently implemented in Chrome 7+, Firefox 3.5+, Safari 5+, Internet Explorer 10+ and Opera 12+.
In case you're using jQuery, then you might be tempted to use its $.val() function as below:
formData.append("myFile", $("#myFileField").val());
But this is incorrect as it doesn't return the whole File object, but merely the file name as String which is utterly useless as it doesn't contain the file contents.
If you don't want to use document.getElementById() for some reason, then use one of the following instead:
formData.append("myFile", $("#myFileField").prop("files")[0]);
formData.append("myFile", $("#myFileField")[0].files[0]);
An alternative is to use the jQuery Form plugin. Your entire form, when written and functioning properly without any line of JavaScript code, will then instantly be ajaxified with just the following line:
$("#formId").ajaxForm(function(response) {
// Handle Ajax response here.
});
It also supports file uploads as well by a hidden iframe trick. See also this jQuery Form documentation for an in-depth explanation. You may only need to change the servlet code to be able to intercept on both normal (synchronous) and Ajax (asynchronous) requests. See also this answer for a concrete example: Simple calculator with JSP/Servlet and Ajax
Either way, the uploaded file should then be available in the doPost() method of a #MultipartConfig servlet as follows:
Part myFile = request.getPart("myFile");
Or if you're still on Servlet 2.5 or older, use Apache Commons FileUpload the usual way. See also this answer for a concrete example: How can I upload files to a server using JSP/Servlet?
It's not possible to send multipart/form-data with XMLHttpRequest (though it is possible in modern browsers, with XHR2. See BalusC's answer).
A common way to achieve what you want is to use a regular form, but in an iframe instead. This way, only the iframe is refreshed on upload.
In my application, user confirms and a jsp page is loaded with confirmation details. I need to email that confirmation.jsp page in the same format.
I tried doing it as below:
In JSP page, surrounded the Body with <div id='content'>
and then through a load function, sent the contents of the page through request paramater:
function load(){
document.getElementById("emailbody").value=encodeURIComponent(document.getElementById('content').innerHTML);
}
But the issue is, the page format has changed and it is not in a HTML format (not at all in readable format).
In your case you should try sending mail on server side in a background thread so that your jsp rendering is not delayed. There are useful server side temlating engines like velocity which can help you achieve your tarhet html and would be easy to send then.
I need to send a particular parameters to Servlet from JSP page. E.g: if I click on the Facebook icon on the web page, then I should send "facebook" as parameter to my Servlet and my Servlet will respond according to the parameter received from JSP file or HTML file.
This is a very open ended question, but the easiest way is to specify parameters in a query string.
If you have the following servlet:
/mysite/messageServlet
Then you can send it parameters using the query string like so:
/mysite/messageServlet?param1=value1¶m2=value2
Within the servlet, you could check your request for parameters using getParameter(name) if you know the name(s), or getParameterNames(). It's a little more involved, specifically with consideration to URL Encoding and statically placing these links, but this will get you started.
String message = request.getParameter("message");
if ("facebook".equals(message))
{
// do something
}
Storing links with multiple parameters in the querystring requires you to encode the URL for HTML because "&" is a reserved HTML entity.
Send Messages
Note that the & is &.
Just wrap the icon in a link with a query string like so
<img src="facebook.png" />
In the doGet() method of the servlet just get and handle it as follows
String name = request.getParameter("name");
if ("facebook".equals(name)) {
// Do your specific thing here.
}
See also:
Servlets info page
One way is to have hidden form variables in your jsp page that get populated on click.
<form action="post" ....>
<input type="hidden" id="hiddenVar" value="">
<a hfref="#" onclick="doSomething();">Facebook</a>
</form>
<script>
function doSomething() {
var hiddenVar= document.getElementById('hiddenVar');
hiddenVar.value = "facebook";
form.submit();
}
</script>
This gives you flexibility to control what gets passed to your servlet dynamically without having to embed urls in your href
I would to get qr code from google chart API in my servlet (e.g. http://chart.apis.google.com/chart?chs=200x200&cht=qr&chld=M&chl=hello).
What libraries (jars) do i need and how should i save the response (maybe to byte array?)
What do you want to do with the image? If you want to just display it to the user, a simple <a href="..."> will suffice. if you want to do some processing (save it in a database, etc), open a connection (new URL("...").openStream()) and then either use ImageIO to get the image (as an image) or read the bytes.
If you're trying to just display the image to the user you don't need to do the HTTP GET request, just print the relevant HTML to the page and the client will do the request:
<img src="<your URL>" />
I've got several Portlets with some links in them, all I want is to hide the URL params. So I thought it would be easy to include some jQuery code, which builds a form for each and binds a click event on it to submit the form.
This does not work. The action request isn't hit for some reason.
Does anyone have a different suggestion for hiding URL parameters?
description of link
<form name="mydataform" id="mydataform" action="/actionurlonyoursite" method="post">
<input type="hidden" name="myparam" value="" />
</form>
<script type="text/javascript">
function handleThisLink()
{
// access the hidden element in which you wish to pass the value of the parameter
dojo.byId("myparam").value = "myvalue";
// the value might be precomputed (while generating this page) or
// might need to be computed based on other data in the page
// submit the form by HTTP POST method to the URL which will handle it.
document.forms['mydataform'].submit();
// also possible to actually send a background AJAX request and publish
// the response to some part of the current page, thus avoiding full
// page refresh
// I used dojo.byId() as a shortcut to access the input element
// this is based on dojo toolkit.
}
</script>
Links fire GET requests by default. You cannot fire HTTP GET requests without passing parameters through the URL. The only what can do this is HTTP POST. All parameters are then included in the request body. But you would need to replace all links by forms with buttons and you need to modify the server side code so that it listens on POST requests instead of GET requests to take actions accordingly.
Javascript can also fire GET requests just in "the background" with help of XMLHttpRequest, but when a client has JS disabled, your application will either break or still display the parameters. Also the client has full control over JS code, so it does not necessarily "hide" the parameters from the client, but only from the browser address bar.
You can using XMLHttpRequest to hide URL parameter or using session variable of servlet container.
Maybe you can using encode url to show complex data to end user.
good luck