download excel generated file - java

I have this button on my html page.
When I click it, exportCOAExcel gets triggered.
Then a excel workbook is generated and save to a path.
I want a prompt to come to say which path you want to download the file to? or save to the deafult 'download' folder location of the browser.
#GetMapping(value = "/coaExport", params = "action=excel")
public void exportCOAExcel(HttpServletRequest request, HttpServletResponse response) throws IOException {
XSSFWorkbook workbook = new XSSFWorkbook();
//loogic to fill up the excel workbook with data
FileOutputStream outputStream = new
FileOutputStream("C:\\Users\\user\\Desktop\\revenue.xls");
workbook.write(outputStream);
outputStream.close();
}

You need to send a content disposition response to the browser, so that it can understand that it is a file to download.
https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Disposition

Related

Load image Dynamically via Java servlet

I am trying to load images from server to my JSP
My files are:
image.jsp
<img src='servlet1' height='300px'/>
DisplayImage.java
public class DisplayImage extends HttpServlet {
public void doGet(HttpServletRequest request,HttpServletResponse response) throws IOException{
response.setContentType("image/jpeg");
ServletOutputStream out;
out = response.getOutputStream();
FileInputStream fin = new FileInputStream("path/to/my/img.jpg");
BufferedInputStream bin = new BufferedInputStream(fin);
BufferedOutputStream bout = new BufferedOutputStream(out);
int ch =0;
while((ch=bin.read())!=-1){
bout.write(ch);
}
bin.close();
fin.close();
bout.close();
out.close();
}
}
Application I'm supposed to build is a Vehicle Directory where I can upload images, and these images are stored in a folder /home/upload/ outside CATALINA
(NB: I didn't use a folder inside project directory coz I am deploying the project via *.war file, which removes every files inside when a new version needs to be deployed.)
I want to display the details and image based on search parameters.
( Edit: I have the file name stored in database when I upload them, so can get the list of image names from DB for a particular vehicle, Since it is stored in folder /home/upload/ , full path will be like /home/upload/fileName.jpg which I need to pass to servlet to load)
Problem I face is that:
image src attribute is specified as servlet1 and the servlet by default serves the image from path defined in DisplayImage.java file
Is there any way that I can pass /another/file/Path.jpg or fileName.jpg to the servlet so that I can display other image files too,
Yeah, In JSP, you can pass your search parameters in request.
Like
<input id="imageSerach" name="imageSerach"/>
<div id="ImageContent"/>
and make ajax call to servlet with imageSearch param.
$.ajax({
url: servleturl,
data: {
imageSerach : $('#imageSerach').val()
},
success: function(responseData){
$('#ImageContent').html('<img src="data:image/png;base64,' + responseData + '" />');
}
});
Servlet :-
public class DisplayImage extends HttpServlet {
public void doGet(HttpServletRequest request,HttpServletResponse response) throws IOException{
String fileName = req.getParameter("imageSerach");
response.setContentType("image/jpeg");
ServletOutputStream out;
File f = new File("path/of/file/"+fileName);
if (f.exists())
out = response.getOutputStream();
FileInputStream fin = new FileInputStream("path/of/file/"+fileName);
BufferedInputStream bin = new BufferedInputStream(fin);
BufferedOutputStream bout = new BufferedOutputStream(out);
int ch =0;
while((ch=bin.read())!=-1){
bout.write(ch);
}
bin.close();
fin.close();
bout.close();
out.close();
else
// no file exit
}
}

How to serve .jasper file with HTTP Server?

I am creating HTTP server with Tomee, i am placed jasper report file (.jasper) in webapp directory. if i access http://localhost:8080/test.jasper in browser, the browser will prompt to download the file.
In my java project i'm creating simple code to access that link and then preview the report. I use async-http-client library for request.
DefaultAsyncHttpClient client = new DefaultAsyncHttpClient();
BoundRequestBuilder brb = client.prepareGet("http://localhost:8765/qa/test.jasper");
Future<InputStream> f = brb.execute(new AsyncCompletionHandler<InputStream>() {
#Override
public InputStream onCompleted(Response resp) {
try {
String[][] data = {{"Jakarta"},{"Surabaya"},{"Solo"},{"Denpasar"}};
String[] columnNames = {"City"};
DefaultTableModel dtm = new DefaultTableModel(data, columnNames);
Map<String,Object> params = new HashMap<>();
JasperPrint jPrint = JasperFillManager.fillReport(
resp.getResponseBodyAsStream(),
params,
new JRTableModelDataSource(dtm)
);
JasperViewer jpView = new JasperViewer(jPrint,false);
jpView.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
jpView.setSize(800, 600);
jpView.setLocationRelativeTo(null);
jpView.setVisible(true);
} catch (JRException ex) {
System.out.println(ex.getMessage());
}
return resp.getResponseBodyAsStream();
}
});
From my code above, i got an error Error loading object from InputStream
normally i can use
InputStream input = MainContext.class.getResourceAsStream(filename);
But i want to replace file input stream with http request (stream too).
How exactly i can serve .jasper file with http server...?
Error loading object from InputStream error came from corrupt InputStream, if i download .jasper file normally via browser and execute the report with JRLoader.loadObjectFromFile(path to file) it doesn't works too, because tomee give corrupt file (the source file not corrupt).
My own solution is read source file as stream, convert it to base64 encode, and serve it via HTTP API protocol.
finput = new FileInputStream(sPath);
byte[] bFile = Base64.getEncoder().encode(IOUtils.toByteArray(finput));
String sFile = new String(bFile);
inside client side, i received it as body string, decode the base64 string, convert it to InputStream and Finally execute the report with InputStream.
byte[] bBody = Base64.getDecoder().decode(sBody);
InputStream mainReport = new ByteArrayInputStream(bBody);
return JasperFillManager.fillReport(mainReport, params);

How to get uploaded excel file from blobstore and how to assign that file to FileInputStream

I am working on project using GWT Java. I uploaded excel file into blobstore in google app engine. I want to read excel file from blobstore. So I have to assign the that excel file from blobstore to FileInputStream.
Example:
FileInputStream file = new FileInpuStream("what is path shall i provide here")
What are the possible ways to assign that excel file from blobstore to FileInputStream?
Any help?
Thanks in Advance
You can use the Apache POI to open the Excel File using your FileInputStream with for example:
XSSFWorkbook wb = new XSSFWorkbook(new FileInputStream(<whatever>));
and work with the POI API to modify the Excelsheet or get the cellinfos. More information to Apache POI: click here.
Or to see a similar problem on SO:click here
The Apache POI XSSFWorkbook accepts either a File or an InputStream.
Assuming that you can access your Blob object via BlobstoreInputStream instance, you can call:
// BlobKey blobKey = initialize your blob key
XSSFWorkbook wb = new XSSFWorkbook(new BlobstoreInputStream(blobKey));
You can access the Blobstore via:
public class Upload extends HttpServlet {
private BlobstoreService blobstoreService = BlobstoreServiceFactory.getBlobstoreService();
#Override
public void doPost(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException {
Map<String, List<BlobKey>> blobs = blobstoreService.getUploads(req);
List<BlobKey> blobKeys = blobs.get("myFile");
if (blobKeys != null && !blobKeys.isEmpty()) {
XSSFWorkbook wb = new XSSFWorkbook(new BlobstoreInputStream(blobKeys.get(0)));
}
}
}
Further reading: Blobstore Java API Overview

Image not being displayed in browser

I am having an image stored at a location say : C:\Users\admin\Desktop\SharedCrpto1\web\RetrievedFiles\FILE310#ST-testemp\abc.png .Now when i try to show it in my jsp page the image is not getting visible even when the path to image is correct.
This image is to be displayed after my server process the browsed image provided by the client.
I tried :
<img src="<%=path%>" alt="No image" />
The image in the particular folder is being created by my servlet like this :
File filesstore = new File("C:\\Users\\admin\\Desktop\\SharedCrpto1\\web\\RetrievedFiles\\FILE310#ST-testemp\\");
if(!filesstore.exists())
{
System.out.println("MAKING DIRECTORY..");
filesstore.mkdirs();
}
To copy one file to this location I did :
FileInputStream fis = new FileInputStream("C:\\test.png");
int xx=fis.available();
byte[] b = new byte[xx];
fis.read(b);
FileOutputStream fos=new FileOutputStream("C:\\Users\\admin\\Desktop\\SharedCrpto1\\web\\RetrievedFiles\\FILE310#ST-testemp\\abc.png");
fos.write(b);
Am i doing something wrong?Please help
From your question what I understood is that You want to read a image file from your local file system & display in a jsp page using
STEP 1
For this you need a servlet or jsp which will read the file and convert to byte[] and again write the byte[] to ServletOutputStream .
STEP 2:
Create a JSP page which have a img tag & it's src should point to servlet url instead of real file path.As img tag's src attribute can take file path or byte stream.In this we are giving it byte stream because file path will not work.
When you call your jsp page it will try to render the img tag and at that time it will call your servlet & get the byte stream of image data .So it will render your image
Image Servlet
#WebServlet("/ImageServlet")
public class ImageServlet extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//place your file path
File imageFile =new File("/home/ashok/Pictures/Siberischer.jpg");
ServletOutputStream outputStream = response.getOutputStream();
byte[] imageBytes = FileUtils.readFileToByteArray(imageFile);
outputStream.write(imageBytes);
outputStream.close();
}
}
JSP PAGE(to display image) In your jsp just write this tag
JspPage is the application name & ImageServlet is the servlet url pattern
<img alt="NO IMAGE" src="/JspImage/ImageServlet">
FileUtils is present Apache Commons IO Library download the jar to your project

file upload with spring MVC

I am uploading file using spring MVC and jquery. Inside my class method I have written
#RequestMapping(value="attachFile", method=RequestMethod.POST)
public #ResponseBody List<FileAttachment> upload(
#RequestParam("file") MultipartFile file,
HttpServletRequest request,
HttpSession session) {
String fileName = null;
InputStream inputStream = null;
OutputStream outputStream = null;
//Save the file to a temporary location
ServletContext context = session.getServletContext();
String realContextPath = context.getRealPath("/");
fileName = realContextPath +"/images/"+file.getOriginalFilename();
//File dest = new File(fileName);
try {
//file.transferTo(dest);
inputStream = file.getInputStream();
outputStream = new FileOutputStream(fileName);
inputStream.close();
outputStream.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Its uploading the file correctly I am using
ServletContext context = session.getServletContext();
String realContextPath = context.getRealPath("/");
to get the path. My first question is , Is this the correct way to get the path and it stores the file somewhere at
workspace/.metadata/.plugins/org.eclipse.wst.server.core/tmp0/wtpwebapps/myproject/images
and when I am trying to display this image on my jsp page using the following code
<img src="<%=request.getRealPath("/") + "images/images.jpg" %>" alt="Upload Image" />
It does not display the image, Its generating the following html
<img src="/home/name/workspace/.metadata/.plugins/org.eclipse.wst.server.core/tmp0/wtpwebapps/myproject/images/images.jpg" alt="Upload Image">
Am I doing the things right? In my project I have to upload large number of files everyday.
Please let me know if you need anything else to understand my question
It will be better if you upload your files in some directory by absolute path(e.g. C:\images\) instead of relative (your approach). Usually, web apps runs on linux mathines on production and it is good practice to make save path configurable.
Create some application property which will holds save path for files(in xml or property file).

Categories