I've created a form and I need the user to enter some info then upload a picture.
So lets say I have something like this:
<form method="post" enctype="multipart/form-data" action="some servlet/filter">
<input type="file" name="logo">
</form>
I need to use java to change that data to a byte[] then to blob so I can insert to a table.
How do I get the data from this form?
A bit of info on this:
I created the page using javascript, then when submitted it will call a java function to handle the data from the form. It seems that when I submit the form the data for the file is not passed over to the servlet.
So far the few methods I've tried have returned null and I'm outta ideas...
Any examples/help is greatly appreciated!
I think the main question I have is where is the file data stored before the java file start working on it? Is a special global variable holding the data or something like that?
You can use the Apache Commons FileUpload library.
The Commons FileUpload package makes it easy to add robust, high-performance, file upload capability to your servlets and web applications.
FileUpload parses HTTP requests which conform to RFC 1867, "Form-based File Upload in HTML". That is, if an HTTP request is submitted using the POST method, and with a content type of "multipart/form-data", then FileUpload can parse that request, and make the results available in a manner easily used by the caller.
If I understood you right, you need something similar to this example:
http://www.servletworld.com/servlet-tutorials/servlet-file-upload-example.html
I used the following tutorial one year ago:
http://balusc.blogspot.com/2009/12/uploading-files-in-servlet-30.html
It looks like it's a lot, but it's actually easy to understand, and it has a lot of good information.
Related
In my JSP page I have DIV.
<div id="100">
ALI
</div>
When I click on this DIV...
$("#100").click(function(){
});
...I need to send the value of the id 100, to a servlet, so that the servlet makes some database java codes, and returns for example, either 1 or 0. How can I do that? and is this the proper way?
Using Ajax, you should call your server using a URL similar to this:
http://localhot:8080/youAppContext/yourServer?id=100
Then, in the servler side, you should retrieve the value that will be in the request with the name "id"
There are out there many tool as jQuery that can help you to do the Ajax petition.
Edited
Well, here you can find a very simple Ajax example using jQuery. In the example, instead call a file (test1.txt) you should invoke a URL (as I described above). Of course, you will need to write some JS code to build your URL (where id be a variable). Once task is done in servlet side, you can return whatever, for example: "done" and display or not this information the HTML as it is done in the example.
Take a look to this Web, there are many links that can help you.
get the value using
var value = $("#100").html();
and pass it to servlet using AJAX
Is there any possible way to send the html form data to java application without using php and asp stuff?
I know we can do this using php and do it before but can i do it directly?
I had used php in my previous app in which user sends his data to php form that saves it into the data base but now i want to directly get the data from the html form.PLease any idea for that?
Maybe you could consider using Java Servlets and JSP for web-based data processing ?
use the html form action attribute to specify an endpoint that will hit a java servlet running inside of a servlet container.
To handle the request in your java class, implement the HttpServlet interface.
http://download.oracle.com/javaee/6/api/javax/servlet/http/HttpServlet.html
If you are posting from a form, them most likely you will want to implement doPost. Or you can implement service as a catch-all
Example:
<form action="/path/to/Servlet" method="post">
<input type="text" name="foo"/>
</form>
....
doPost(HttpServletRequest request, HttpServletResponse respnose) {
// set String foo to the form element named "foo"
String foo = request.getParameter("foo");
// now do whatever you need to w/ foo
}
Try Tomcat with Java Servlets. You need to:
write a class that extends HttpServlet
override the "doPost(HttpServletRequest, HttpServletResponse)" or "doGet(...)" methods
write a web.xml file mapping the web page URL to the servlet handling the request
compile and bundle everything together as required.
It'll take a little doing to get everything in the right place but it's not too hard. See the Tomcat documentation for further details. Good luck.
You can send the data by using jsp or by sending it in a link like www.google.com?q=usa
and parse it on other side
I've a problem with the methode blobstoreService.getUploadedBlobs(). I've a JSP page in wich one I set an uploader like this :
<formname='form' action='<%= blobstoreService.createUploadUrl("/Edit_Engine") %>' method='POST' enctype='multipart/form-data' >
<input label='...' multiple='false' name='myFile' />
//...and multiple input for text
</form>
and I retrieve this code with my servlet :
java.util.Map<String,BlobKey> blobs = blobstoreService.getUploadedBlobs(req);
BlobKey blobK = blobs.get("myFiles[]"); //I don't know why I need to add the characters 's[]' at the end...
But the behavior is strange. The first time I upload an image, everything works. However, the second time, I send my form without uploading somehting (only text data), and then my java code finds a BlobKey. But this BlobKey seems to be the previous sended data, or a corrupted data.
I mean that not normal, because when I deploy this version on my localhost, if the form uploads no file the method getUploadedBlobs returns an empty HashMap. However, when I deploy on google servers, if the form uploads no file, the method getUploadedBlobs seems to return a HashMap with wrong data.
Could you help me? Or tell me if this behaviro is normal...
Many thanks,
bat
If you're getting a valid BlobKey, then myFiles[] is most likely the name given to the file input field in the form. Is that the case? That seems like an odd name for an input field. Are you using a template library to help generate HTML from the JSP?
I need to implement a servlet that uploads files to a server, I realize everyone says it has to be a POST method in regard to uploading files and not with GET method. However is there a way to upload a file and have the parameters of the request show up in the url even if the request is coming from POST method? If not, is there another approach?
Currently my servlet using post method is http://example.com/FileUpload/UploadFile
What I want is somehting like http://example.com/FileUpload/UploadFile?id=125&fileNum=5
Thanks for your input.
Simply POST to
http://example.com/FileUpload/UploadFile?id=125&fileNum=5
instead of
http://example.com/FileUpload/UploadFile
There is no such restriction that you cannot post to an URL having parameters. You can process the post data as you are doing now, plus, you can get the get parameters also.
I think it would not be an elegant solution, but you could use JavaScript to alter the action of the form element before submitting it to include querystring parameters.
The form will be something like:
<form method="POST" id="myForm" onSubmit="submitMyForm(this)>
<input type="text" id="id">
Then you will need JavaScript to change the action element of the form:
function submitMyForm(theForm) {
theForm.action="http://example.com/FileUpload/UploadFile?id=" +
getElementById("id").value;
theForm.submit();
}
Is there some reason you cannot just submit the parameters with post and pull them out on the server side?
Alternatively, if you do a multipart/form-data post you can include multiple parameters along with your file. The parameters are sent as part of the post body, along with the file.
You can send parameters and files in the POST. For example in the html you can have a form with this values, they can be of hidden type.
In the servlet you can get the values in the same way you do using the GET.
It is also better to use the POST method because the user can't change the value in the URL direction bar.
I've a HTML table on my JSP page, that I want to be exported to Excel on a button click.
What would be the best way of going about this?
(For ex., how would I do this using may be a jQuery function?)
Any code examples for demo purposes should be great.
I would recommend Apache POI, we've been using it for years, never had any problems.
Alot of examples online to get a good start, and the documentation on the site is also good: http://poi.apache.org/spreadsheet/quick-guide.html
Rather export to CSV format. It's supported by Excel as well. Exporting to a fullworthy XLS(X) format using for example Apache POI HSSF or JExcepAPI is slow and memory hogging.
Exporting to CSV is relatively simple. You can find a complete code example in this answer.
As to exporting to files using JavaScript, this is not possible without interaction of Flash or the server side. In Flash there's as far only the Downloadify library which can export to simple txt files. Further, ExtJs seems to have a CSV export library, but I can't find any feasible demo page.
You can parse the table using a library like http://jsoup.org/
After you get the data, you can store it in Excel-compatible format (CSV), or using Java Excel library for that like POI, or using JDBC to write data into Excel sheet, see this example:
Password Protected Excel File
I also spend lot of time to convert html to excel after lot of R & D i found following easiest way.
create hidden field and in that pass your html data to your servlet or controller for e.g
<form id="formexcel" action="" method="post" name="formexcel">
<input type="hidden" name="exceldata" id="exceldata" value="" />
</form>
on your button of href click call following function and pass your html data using in document.formexcel.exceldata.value and your servlet or controller in document.formstyle.action
function exportDivToExcel() {
document.formexcel.exceldata.value=$('#htmlbody').html();
$("#lblReportForPrint").html("Procurement operation review report");
document.formstyle.method='POST';
document.formstyle.action='${pageContext.servletContext.contextPath}/generateexcel';
document.formstyle.submit();
}
Now in your controller or servlet write following code
StringBuilder exceldata = new StringBuilder();
exceldata.append(request.getParameter("exceldata"));
ServletOutputStream outputStream = response.getOutputStream();
response.setContentType("application/vnd.ms-excel");
response.setCharacterEncoding("UTF-8");
response.setHeader("Content-Disposition", "attachment;filename=\"exportexcel.xls\"");
outputStream.write(exceldata.toString().getBytes());
Excel can load CSV (comma-separated value) files, which are basically just files with everything that would go into separate Excel cells separated by comma.
I don't know enough about how jQuery can handle pushing information into a file that you would download, but it seems a jQuery library has been written that at least transforms html tables to CSV format, and it is here:
http://www.kunalbabre.com/projects/table2CSV.php
Edit (February 29, 2016):
You can use the table2csv implementation above in conjunction with FileSaver.js (which is a wrapper for the HTML5 W3C saveAs() spec).
The usage will end up looking something like:
var resultFromTable2CSV = $('#table-id').table2CSV({delivery:'value'});
var blob = new Blob([resultFromTable2CSV], {type: "text/csv;charset=utf-8"});
saveAs(blob, 'desiredFileName.csv');
Exporting to Excel file format with JQuery is impossible.
You can try with Java. There are a lot of libraries to do that.
You would have to create something on the server-side (like a servlet) to read the html and create the excel file and serve it back to the user.
You could use this library to help you do the transformation.
I can suggest you to try http://code.google.com/p/gwt-table-to-excel/, at least the server part.
I have been using the jQuery plugin table2excel. It works very well and no serverside coding is needed.
Using it is easy. Simply include jQuery
<script src="http://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
Now include the table2excel script (Remember to change the src destination to match yours)
<script src="dist/jquery.table2excel.min.js"></script>
Now simply call the script on the table you want exportet.
$("#yourHtmTable").table2excel({
exclude: ".excludeThisClass",
name: "Worksheet Name",
filename: "SomeFile" //do not include extension
});
It's also easy to attach to a button like so:
$("button").click(function(){
$("#table2excel").table2excel({
// exclude CSS class
exclude: ".noExl",
name: "Excel Document Name"
});
});
All examples are taken directly from the authors github page and from jqueryscript.net