How to upload a zip file using Java? - java

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)

Related

Bootstrap progress bar visible when downloading file from java servlet

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();

How do I email an HTML report (as an attachment) with images embedded?

I am creating a report with ExtentReports to be emailed out to team members outside of the domain. I use a screenshot method (below) to save screenshots of test failures. They are stored in a child folder to the ExtentReports HTML report.
I attach the report to an email, and in it, the images display fine for team members on the domain with folder permission. But I am at a loss for how to allow people outside of that folder's permissions, to see the images embedded in the report. This is the HTML for the image, directly referencing that file.
<img class="report-img" data-featherlight="file:///\\domain.local\files\QA\Projects\AutomationReports\ExtentScreens\1486487870116.jpg" src="file:///\\domain.local\files\QA\Projects\AutomationReports\ExtentScreens\1486487870116.jpg">
Here is my screenshot method.
public static String CaptureScreen(WebDriver driver) {
String ImagesPath = "\\\\domain.local\\files\\QA\\Projects\\AutomationReports\\ExtentScreens\\"
+ new Date().getTime();
TakesScreenshot oScn = (TakesScreenshot) driver;
File oScnShot = oScn.getScreenshotAs(OutputType.FILE);
File oDest = new File(ImagesPath + ".jpg");
// System.out.println(ImagesPath);
try {
FileUtils.copyFile(oScnShot, oDest);
} catch (IOException e) {
System.out.println(e.getMessage());
}
return ImagesPath + ".jpg";
}
I have 2 unrelated ideas on how to fix this. But I need some help getting started with either of them. I'm open to other suggestions.
Embed images directly into the HTML report or somehow send a folder containing screenshots with the HTML report. However, the HTML will still reference my original location and the images will be broken.
Share the folder containing images with Everyone, Guest, and Anonymous User, so people outside of the domain can open HTML that references this location. I don't know how to set these permissions, and I'm not even sure that doing so will allow an external user to view HTML referencing the location.
Please try with base64 encoding it will definitely work.
Also, please check your browser support.
Try this:
<img src="data:image/jpeg;base64,/9j/4AAQxxxxxxxx...." />
Depending on what browsers you need to support, you could embed your images in base64. like this :
<img src="data:image/jpeg;base64, LzlqLzRBQ...<!-- base64 data -->" />
Here is a tool to encode your images
You can embed base64 encoded images directly into HTML document.
<img src="data:image/jpeg;base64,/9j/4AAQxxxxxxxx...." />
You can create a multipart/report message with the images included as additional body parts in the message. The JavaMail FAQ includes this sample code:
Multipart multipart = new MimeMultipart("related");
MimeBodyPart htmlPart = new MimeBodyPart();
// messageBody contains html that references image
// using something like <img src="cid:XXX"> where
// "XXX" is an identifier that you make up to refer
// to the image
htmlPart.setText(messageBody, "utf-8", "html");
multipart.addBodyPart(htmlPart);
MimeBodyPart imgPart = new MimeBodyPart();
// imageFile is the file containing the image
imgPart.attachFile(imageFile);
// or, if the image is in a byte array in memory, use
// imgPart.setDataHandler(new DataHandler(
// new ByteArrayDataSource(bytes, "image/whatever")));
// "XXX" below matches "XXX" above in html code
imgPart.setContentID("<XXX>");
multipart.addBodyPart(imgPart);
message.setContent(multipart);
We should have a class file as below
public class GetScreenShort {
public static String capture(WebDriver driver,String screenShotName)
throws IOException
{
TakesScreenshot ts = (TakesScreenshot)driver;
String dest = ts.getScreenshotAs(OutputType.BASE64);
return "data:image/jpg;base64, " + dest ;
}
}
The same class has to be called as below
String screenShotPath = GetScreenShort.capture(webdriver,
"screenShotName");

read a txt file that is dynamically fill

i read a file txt with java code and then i display it's content with js in html page but the content changes over time so i can't acces to file if the content was change:
the java code :
the methode that read file and return a string that containing the txt file content
public static String getLog() throws IOException{
StringBuilder sb = new StringBuilder();
String path=logging.getRealPath();
InputStream ips;
try {
ips = new FileInputStream(path);
InputStreamReader ipsr=new InputStreamReader(ips);
BufferedReader br=new BufferedReader(ipsr);
String ligne;
while((ligne=br.readLine())!=null){
sb.append("<br>"+ligne);
br.close();
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return sb.toString();
}
and the js function
<script type="text/javascript">
function getALLLog(){
var arrayNew = "<%=logging.getLog()%>";
document.getElementById("log").innerHTML=arrayNew;
}
</script>
the html code is like:
<div style="padding:15px" >
<span id="ALL" style="cursor: pointer;font-weight:bold;" onclick="getALLLog()">ALL</span>
</div>
<div id="log"></div>
so the content is displayed for the first time after filling the file nothing appears
Your java getLog() function gets evaluated only once when the server generates html. After that javascript variable arrayNew holds the log contents. When you click on the ALL span you don't actually call your java server - only client-side javascript, so you just showing the same content over and over.
If you want server to be called when you click some button on the web page you need to use AJAX or just refresh the entire page.

Download file in JSP with AJAX

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

How do i convert blob to image displayed in a JSP

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>

Categories