I want to show the BootStrap's progress bar while am downloading file from Sevlet API.
Application architecture designed like - From React JS using SuperAgent am invoking Servlet API which is responsible for writing a Excel file and it will return that Excel file to the SuperAgent to download the same.
While doing this process i want to show the BootStrap's progress bar for UX.
Please find my code below
Servlet API code for writting a Excel file and return the same to SuperAgent
try {
String reportname = "Invoice";
resp.setContentType("application/vnd.ms-excel");
resp.setHeader("Content-Disposition", "attachment; filename=" +
reportname + ".xls");
HSSFWorkbook workbook1=service.getCommercialInvoiceService(id);
ByteArrayOutputStream outByteStream = new ByteArrayOutputStream();
workbook1.write(outByteStream);
byte [] outArray = outByteStream.toByteArray();
int fileSize=outArray.length;
outStream = resp.getOutputStream();
outStream.write(outArray);
outStream.flush();
outStream.close();
resp.setHeader("Content-Length", ""+fileSize);
} catch (IOException ioe) {
throw new ServletException(ioe);
}
ReactJS method which is using SuperAgent to download file from Servlet API
handleInvoice(e) {
e.preventDefault()
var item = this.state.item;
var lines = item.order;
var request = require('superagent');
var apiBaseUrl = "api/Invoice";
var req = request.get(apiBaseUrl);
req.query({ item : item.id})
req.end(function(err,res) {
if(err) {
alert(" error"+err);
confirmAlert({
message: 'Invoice is not prepared properly.....',
confirmLabel: 'Ok',
});
}
else {
window.location= 'api/Invoice?item=' + item.id,'';
element.click();
}
});
}
I want to show the below bootstrap's progress bar while downloading the file.
<div class="progress">
<div class="progress-bar" role="progressbar" aria-valuenow="" aria-
valuemin="0" aria-valuemax="100" style="width: 60%;">
</div>
</div>
How do i integrate progress bar in ReactJS code ( SuperAgent is invoking the Java Servlet API).
Your code which writes the headers and data is as follows..
int fileSize=outArray.length;
outStream = resp.getOutputStream();
outStream.write(outArray);
outStream.flush();
outStream.close();
resp.setHeader("Content-Length", ""+fileSize);
Note that the content length is being set after the output stream has been written to. HTTP responses consist of a series of headers followed the content, which you write to via the OutputStream. Here you have simply set the content length after streaming the content. So this value is not sent at the start of the response.
The content length of the output is not mandatory (it might not be known by the process streaming it). But of course you can't produce a progress bar unless you know the length of the data. Simply set the content length before writing the data so it makes it into the response headers.
int fileSize=outArray.length;
resp.setHeader("Content-Length", ""+fileSize);
outStream = resp.getOutputStream();
outStream.write(outArray);
outStream.flush();
outStream.close();
Related
I have a jsp that makes an AJAX call to a helper jsp which calls a java bean that creates an image. The helper JSP then loads the image into a byte array encodes it to Base64 using Apache commons and returns the string.
File imageFile = new File("test.png");
response.setHeader("Content-Type", getServletContext().getMimeType(imageFile.getAbsolutePath()));
response.setHeader("Content-Length", String.valueOf(imageFile.length()));
FileInputStream is = new FileInputStream(imageFile);
byte[] buffer = new byte[(int)imageFile.length()]; // 32k buffer
int offset = 0;
while ( offset < buffer.length ) {
int count = is.read(buffer, offset, buffer.length - offset);
offset += count;
}
byte[] encoded = Base64.encodeBase64(buffer);
String encodedFile = Base64.encodeBase64String(encoded);
out.print(encodedFile);
out.flush();
Here is the javascript that makes and receives the request for the image:
function getContourImage(startDate, stopDate){
$.ajax("services/contour.jsp", {
data: {
startDate: startDate,
stopDate: stopDate
},
dataType: "json",
traditional: true,
success: contourImageHandler()
});
}
function contourImageHandler(resp){
alert("resp: " + resp);
$( "#plot" ).attr("src","data:image/png;base64," + resp);
}
This is the image display area in the html:
<div id="imageDisplay" name="imageDisplayDiv"
img name="contourImageLocation"
id="plot" src="images/test.png" width="1200" height="1200">
I can see the response in the firebug panel and it seems to have data. The alert statement in the ajax response handler says the response is undefined and no image is placed in the plot location. Does anyone know what I have done wrong?
For the 'displaying the image' part of your problem you can go through this:
http://danielmclaren.com/node/90
Also, it would be better if 'helper jsp' work is moved to a Servlet as you may get additional/junk spaces and line breaks in a jsp response.
I have a simple JSP page, which contains 2 buttons: View and Export. When View button is clicked I will fetch data from DB, keep a copy into session and write an HTML code into a label with the data. Later when user clicks Export I want to generate an excel file in the server(with the data from session) and download it to clientside.
Excel file is successfully created at serverside. I am using an AJAX request from clientside to download Excel file from server.
JSP code:
try{
String filepath=ExportToExcel(session.getAttribute("InvestmentDetails"));
//Setting file to download
response.setContentType( "application/x-download");
response.setHeader("Content-Disposition","attachment; filename=\"SIPInvestment_531.xls\"");
response.setStatus(200);
InputStream in = null;
ServletOutputStream outs = response.getOutputStream();
try {
File filetodownload=new File(filepath);
response.setContentLength(Integer.parseInt(String.valueOf(filetodownload.length())));
in = new BufferedInputStream(new FileInputStream(filetodownload));
int ch;
while ((ch = in.read()) != -1) {
outs.print((char) ch);
}
}
finally {
if (in != null) in.close();
}
outs.flush();
outs.close();
}
catch(Exception ex){
str=ex.getMessage();
}
Here is the Javascript:
xmlhttp=new XMLHttpRequest();
xmlhttp.onreadystatechange=function(){
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
}
}
xmlhttp.open("POST","/SIP/rptClientInvestmentDetails.jsp?requesttype=export",false);
xmlhttp.send();
The request reaches on JSP page. And without any exception it writes to response outputstream. But no download is pop up from browser. What can be the problem?
Ajax should be used for meta-languages, not for binary files.
A simple
<a href="/SIP/rptClientInvestmentDetails.jsp?requesttype=export"
target="_blank">Export</a>
is all you need.
If you make sure you said the response.setHeader("Content-Disposition","attachment you should drop the target-attribute as BalusC suggested.
I think you can use location.href="Provide the java class function name".This will transfer the control from jsp to java function without using the ajax call
I am trying to retrieve images from database.
Currently i was able to show :
`com.mysql.jdbc.Blob#2aba2aba `
in my jsp output.
May i know how to convert that into an image?
i have use the below to call out the above
photo[i].getPhotoFileData();
This is more of an issue with the way HTML documents work than with your JSP. You need to understand that HTML doesn't embed images directly. Instead, it uses <img> tags to reference images hosted at different URLs.
In order to display an image stored in a database on an HTML page you're going to need a separate servlet that can handle requests for the image. Your JSP should render an HTML document like the following:
<html>
<head>
...
</head>
<body>
...
<img src="www.mydomain.com/images/1234.png" />
...
</body>
</html>
Then you would create a separate servlet to handle all the requests to /images which would make a database call and send the raw bytes from the blob it gets back to the response's output stream. Make sure you also set the Content-Type header correctly based on what image encoding you're using.
In order to send the image back to the requester you have one of two options. You can get the blob's bytes as an array and write that to the OutputStream (e.g. out.write(blob.getBytes(0,blob.length());). Or you can use the getBinaryStream() method and then copy bytes from the InputStream to the OutputStream. Here's an example of that:
public static void copy(Blob from, OutputStream to)
throws IOException {
byte[] buf = new byte[4096];
try(InputStream is = from.getBinaryStream()) {
while (true) {
int r = is.read(buf);
if (r == -1) {
break;
}
to.write(buf, 0, r);
}
}
}
NB: This code has not been tested or even compiled, it should only be used as a starting point.
You're getting a Blob object - not it's contents. If you want to get raw byte data you have to ask the Blob object for it, e.g.:
Blob blob = photo[i].getPhotoFileData();
byte[] data = blob.getBytes(0, blob.length());
If you want to create an image on the fly, then just call:
BufferedImage img = ImageIO.read(new ByteArrayInputStream(data));
You can then save the image or ... actually I don't know what else. Thing. Stuff. Display it. Print. Limitless possibilities! Just like at zombo.com!
first convert blob to input stream to string . then use that String instead of image URL .
Converting blob to String
try {
Blob blob = staticOffer.getImage(); //blob of image from db
strOut = new StringBuffer();
String aux;
BufferedReader br;
br = new BufferedReader(new InputStreamReader(blob.getBinaryStream()));
while ((aux=br.readLine())!=null) {
strOut.append(aux);
}
offerPicStr = strOut.toString();
} catch (Exception e) {
e.printStackTrace();
}
Now use that string it html/jsp in following way
<img src="data:image/jpeg;base64,${offerPicStr}" width="100" height="100"></img>
How to save the image on the servlet?
And how to send it back to a web page?
This servlet receives a request from JS with a file input (image).
I want to save the picture (maybe on a list -db not needed) and then servlet sends back a response with everything he received (together with the photo).
Is there any suggestion?
I tried unsuccessfully with this code:
response.setContentType("text/html; charset=UTF-8");
PrintWriter out = response.getWriter();
out.println("</HEAD>\n");
out.println("<BODY>\n" +
"<TABLE>\n" +
"<TR>\n" +
"<TH>--Asked Infos--" +
"<TH>--Your Input--");
/*for typical inputs from the form */
Enumeration paramNames = request.getParameterNames();
while( paramNames.hasMoreElements() )
{
String paramName = (String)paramNames.nextElement();
out.println("<TR><TD>" + paramName + "\n<TD>");
String[] paramValues = request.getParameterValues(paramName);
String paramValue = paramValues[0];
if ( paramValue.length() == 0 ){
/* .... store a default photo from servlet 'cause user didn't give file...*/
}
out.print(paramValue);
}
/* file input */
String fileName = request.getParameter("avatar");/*avatar is the file input name from JS*/
FileInputStream fis = new FileInputStream(new File("C:\\"+fileName));
BufferedInputStream bis = new BufferedInputStream(fis);
BufferedOutputStream output = new BufferedOutputStream(response.getOutputStream());
for (int data; (data = bis.read()) > -1;)
{
output.write(data);
}
out.println("</TABLE>\n</BODY></HTML>");
The way to upload a file is creating a form with <input type="file" name="avatar">. For the actual upload inside the servlet one should better use an apache or Spring upload servlet filter. For that code search in the internet - a good excercise.
A link here, for support in the newest JavaEE6 support (apache Geronimo server, but Glassfish should be the same). Before JEE6 one needed extra code, a servlet filter.
I trying to upload a zip file. In my project i am using DWR in the client side and Java in server side. As i have seen in DWR tutorials for uploading data(Its not in their website. They are providing it with dwr.rar bundle) they getting input by the below lines.
var image = dwr.util.getValue('uploadImage');
var file = dwr.util.getValue('uploadFile');
var color = dwr.util.getValue('color');
dwr.util.getValue() is a utility to get the value of any element, in this case a file object.//Mentioned in the tutorial.
So, i get a zip file using that utility by the below code.
Javascript:
function uploadZip(){
var file = dwr.util.getValue("uploadFile");
dwr.util.setValue("uploadFile", null);
DataUpload.uploadData(file, function(data){
if(data != null){
$("#zipURL").html("<p>Upload Completed!!!</p>");
$("#zipURL").append("Location: "+data.path2);
}
});
}
HTML:
<html>
<head>ZIP Uploader
</head>
<body>
<table>
<tr><td>Select File: </td><td><input type="file" id="uploadFile" /></td>
<tr><td><input type="button" value="Upload" onclick="uploadZip()" /></td></tr> </table>
<div id="result"><span id="imgURL"></span>
<span id="zipURL"></span></div>
</body>
</html>
The Java Code is:
public class DataUpload {
private static String DATA_STORE_LOC = "D:/BeenodData/Trials/";
public Path uploadData(InputStream file) throws IOException{//In the tutorial the
//parameters are in type of BufferedImage & String.
//They used it for image and text file respectively.
//In an another example(out of DWR site) they used InputStream for receiving
//image
try {
byte[] buffer = new byte[1024];
int c;
File f2 = new File(DATA_STORE_LOC+dat+".zip");
path.setPath2(DATA_STORE_LOC+dat+".zip");
FileOutputStream fos = new FileOutputStream(f2);
c = file.read();
System.out.println(c);
while ((c = file.read()) != -1) {
fos.write(c);
}
file.close();
fos.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return path;
}
This code runs without error. But the output is a Empty zip file. I know i doing something wrong. I unable to find that.
Actually, i am receiving a zip file as
InputStream.
How should i have to write a
InputStream(a zip file) to a zip.file
using java?
What will happen if i set the java
method parameter as ZipFile file? I
didnt tried it, yet because, i am
still searching a good tutorial to
learn about it.
Any Suggestion or Links would be more appreciative!!!!!
Thanks in Advance!!!
Here you have 2 examples about creating a ZIP file:
http://www.java2s.com/Tutorial/Java/0180_File/0601_ZipOutputStream.htm
Here is an example about reading a ZIP file:
http://www.kodejava.org/examples/334.html
I have also implemented the Same kind of backend Code in Java, and I was facing the same Issue of Zip file being made, but its content being empty.
Later I found that the Request I was making to API, in that the file I was Attaching was not in --data-binary format. So, I then made the request in this Format.
curl --data-binary #"/mnt/c/checknew.zip" http://localhost/api/upload
I am not sure what request format you are making either in multipart/form-data or Base-64 encoded.
My code worked when I made a Base-64 encoded Request (i.e --data-binary)