I have used a fileDownloadActionListener for opening a jasper report from an ADF form. First time, it's opening correctly. But the second time onwards it gives an error message on the application saying, "The file was not downloaded or was not downloaded correctly."
This is my code:
public void reportAction(FacesContext ctx,OutputStream output) throws FileNotFoundException,NamingException,
SQLException, IOException, JRException,
ClassNotFoundException,
InstantiationException,
IllegalAccessException,StreamCorruptedException {
File input = null;
Connection conn = null;
String branchId = getBranchId().getValue().toString();
Map reportParameters = new HashMap();
reportParameters.put("branchId", branchId);
bindings = this.getBindings();
ctx = FacesContext.getCurrentInstance();
HttpServletResponse response = (HttpServletResponse)ctx.getExternalContext().getResponse();
ServletOutputStream servletOutputStream;
servletOutputStream = response.getOutputStream();
String reportPath = ctx.getExternalContext().getInitParameter("reportpath");
input = new File(reportPath+"testJob.jasper");
byte[] bytes= null;
if(bindings!=null){
OperationBinding ob = bindings.getOperationBinding("getCurrentConnection");
ob.execute();
conn = (Connection)ob.getResult();
System.out.println("Report Path===========>"+input.getPath().toString());
if(input.getPath()!=null&&reportParameters!=null&&conn!=null){
JRPdfExporter pdfExporter = new JRPdfExporter();
bytes = JasperRunManager.runReportToPdf(input.getPath(), reportParameters, conn);
JasperPrint print = JasperFillManager.fillReport(input.getPath(),reportParameters,conn);
pdfExporter.setParameter(JRExporterParameter.JASPER_PRINT, print);
pdfExporter.setParameter(JRExporterParameter.OUTPUT_FILE_NAME, input.getPath());
pdfExporter.exportReport();
response.addHeader("Content-disposition", "attachment;filename=testJob1.pdf");
response.setContentType("application/pdf");
response.setContentLength(bytes.length);
File file = new File(input.getPath());
output = response.getOutputStream();
servletOutputStream.write(bytes, 0, bytes.length);
FileInputStream fis = new FileInputStream(file);
BufferedInputStream bui = new BufferedInputStream(fis);
int readBytes = 0;
while ((readBytes = bui.read()) != -1)
output.write(readBytes);
bui.close();
fis.close();
servletOutputStream.flush();
servletOutputStream.close();
ctx.responseComplete();
}
}
else{
ctx.addMessage(null,new FacesMessage("No bindings configured for this page"));
}
}
Related
I've taken over a project where the file upload functionality is broken. Currently when a file is uploaded it is converted to a byteArray like so and then stored in a SQL table
public static byte[] saveAttachment(String filePath) throws IOException{
InputStream inputStream = new FileInputStream(filePath);
byte[] buffer = new byte[1048576];
int bytesRead;
ByteArrayOutputStream output = new ByteArrayOutputStream();
while((bytesRead = inputStream.read(buffer)) != -1){
output.write(buffer, 0 , bytesRead);
}
inputStream.close();
return output.toByteArray();
}
I can't say I agree with the approach that has been taken but alas I must work with it. My question becomes how do I go about retrieving this file to display?
I have read
https://wiki.apache.org/tapestry/Tapestry5HowToStreamAnExistingBinaryFile
And tried (which didn't work)
#OnEvent(component="viewAttachment")
private Object viewAttachment(){
final File getFile();
final OutputStreamResponse response = new OutputStreamResponse() {
public String getContentType() {
return "image/jpg";
}
public void prepareResponse(Response response) {
response.setHeader ("Content-Disposition", "attachment; filename=\"" + file.getName() + "\"");
}
#Override
public void writeToStream(OutputStream out) throws IOException {
try {
InputStream in = new FileInputStream(file);
IOUtils.copy(in,out);
in.close();
} catch (Exception e) {
throw new RuntimeException(e);
}
}
};
return response;
}
However I am not sure this is the proper/optimal solution.
Assuming that row.getBytes() returns your image as byte array, and row.getName() is image name:
return new StreamResponse() {
#Override
public String getContentType() {
return "image/jpeg";
}
#Override
public InputStream getStream() throws IOException {
return new ByteArrayInputStream(row.getBytes());
}
#Override
public void prepareResponse(Response response) {
response.setHeader("Content-Disposition", "attachment; filename=\"" + row.getName() + "\"");
}
};
Its better to save the file in a location and save the location in the database. This will help to have size of database.
Also file is available and can retrieve easily without heavy database object.
Or you can add the BLOB column in database and store the file in database.
Convert file into File object
File image = new File("D:\\a.gif");
FileInputStream fis = new FileInputStream(image);
stmt.setBinaryStream(1, fis, (int) image.length());
Add retrieve it using
File image = new File("D:\\java.gif");
FileOutputStream fos = new FileOutputStream(image);
byte[] buffer = new byte[1];
InputStream is = resultSet.getBinaryStream(3);
while (is.read(buffer) > 0) {
fos.write(buffer);
}
fos.close();
I am a newbie in java and I want to display all the images from a system folder, viz. E://New
I am using a servlet but don't know how to proceed using it.
The servlet is:
response.setContentType("image/jpeg");
ServletOutputStream out;
out = response.getOutputStream();
FileInputStream fin = new FileInputStream("E:\\new\\");
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();
Thanks.
I think it can be made by this code
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
response.setContentType("image/jpeg");
String pathToWeb = getServletContext().getRealPath(File.separator);
File f = new File(pathToWebToyourfile);
BufferedImage bi = ImageIO.read(f);
OutputStream out = response.getOutputStream();
ImageIO.write(bi, "jpg", out);
out.close();
}
String fileName = "/CSVLogs/test";
String fileType = "csv";
resp.setContentType(fileType);
resp.setHeader("Content-disposition","attachment; filename=test.csv");
File my_file = new File(fileName);
OutputStream out = resp.getOutputStream();
FileInputStream in = new FileInputStream(my_file);
byte[] buffer = new byte[4096];
int length;
while ((length = in.read(buffer)) > 0){
out.write(buffer, 0, length);
}
in.close();
out.flush();
I need to download a csv file but it seems to return "java.lang.IllegalStateException: WRITER"
<form enctype="multipart/form-data" action="/TestServlet/ConfigServlet?do=downloadLogs" method="post" style="height:68px;">
UPDATE
resp.setContentType("application/octet-stream");
try
{
OutputStream outputStream = resp.getOutputStream();
InputStream in = StorageUtil.getInstance().getFile("/CSVLogs/test.csv").getInputStream();
/* InputStream in = StorageUtil.getInstance().getCSVLogsZip().getInputStream();*/
byte[] buffer = new byte[4096];
int length;
while ((length = in.read(buffer)) > 0){
outputStream.write(buffer, 0, length);
in.close();
outputStream.flush();
}
}
catch(Exception e) {
System.out.println(e.toString());
}
I still get the same error.
java.lang.IllegalStateException: WRITER
(drunk) Why am I getting this error >_<
Try this:
public void doGet(HttpServletRequest request, HttpServletResponse response)
{
response.setContentType("text/csv");
response.setHeader("Content-Disposition", "attachment; filename=\"test.csv\"");
try
{
OutputStream outputStream = response.getOutputStream();
FileInputStream in = new FileInputStream(my_file);
byte[] buffer = new byte[4096];
int length;
while ((length = in.read(buffer)) > 0){
outputStream.write(buffer, 0, length);
in.close();
outputStream.flush();
}
}
catch(Exception e)
{
model.closeConnection();
System.out.println(e.toString());
}
}
public void downloadFile(HttpServletResponse response){
String sourceFile = "c:\\source.csv";
try {
FileInputStream inputStream = new FileInputStream(sourceFile);
String disposition = "attachment; fileName=outputfile.csv";
response.setContentType("text/csv");
response.setHeader("Content-Disposition", disposition);
response.setHeader("content-Length", String.valueOf(stream(inputStream, response.getOutputStream())));
} catch (IOException e) {
logger.error("Error occurred while downloading file {}",e);
}
}
And the stream method should be like this.
private long stream(InputStream input, OutputStream output) throws IOException {
try (ReadableByteChannel inputChannel = Channels.newChannel(input); WritableByteChannel outputChannel = Channels.newChannel(output)) {
ByteBuffer buffer = ByteBuffer.allocate(10240);
long size = 0;
while (inputChannel.read(buffer) != -1) {
buffer.flip();
size += outputChannel.write(buffer);
buffer.clear();
}
return size;
}
}
java/servlet code you supplied works perfectly fine.
i call the servlet CSVD as below:
< form enctype="multipart/form-data" action="CSVD" method="post" style="height:68px;">
<input type="submit" value="submit" />
< /form>
or through anchor this way < a href="/CSVDownloadApp/CSVD">click here to download csv< /a>
possibly your error is coming for a different reason.
Try this:
response.setContentType("application/x-rar-compressed");
response.setHeader("Content-Disposition", "attachment; filename=\"test.csv\"");
For writing the file in OutputStream, try following
FileInputStream fis = new FileInputStream("your_csv_file.csv");
byte[] b = new byte[fis.available()];
outputStream.write(b);
outputStream.flush();
outputStream.close();
I have two node on production environment. I have placed pdf files at one server and want to read it from both server. when am calling 'file' method directly pdf get displayed in browser but when i call 'pdfFiles' nothing is displayed in browser.
public Resolution file(){
try {
final HttpServletRequest request = getContext().getRequest();
String fileName = (String) request.getParameter("file");
File file = new File("pdf file directory ex /root/pdffiles/" + fileName);
getContext().getResponse().setContentType("application/pdf");
getContext().getResponse().addHeader("Content-Disposition",
"inline; filename=" + fileName);
FileInputStream streamIn = new FileInputStream(file);
BufferedInputStream buf = new BufferedInputStream(streamIn);
int readBytes = 0;
ServletOutputStream stream = getContext().getResponse().getOutputStream();
// read from the file; write to the ServletOutputStream
while ((readBytes = buf.read()) != -1)
stream.write(readBytes);
} catch (Exception exc) {
LOGGER.logError("reports", exc);
}
return null;
}
public Resolution pdfFile() {
final HttpServletRequest request = getContext().getRequest();
final HttpClient client = new HttpClient();
try {
String fileName = (String) request.getParameter("file");
final String url = "http://" + serverNameNode1 //having pdf files
+ "/test/sm.action?reports&file=" + fileName;
final PostMethod method = new PostMethod(url);
try {
client.executeMethod(method);
} finally {
method.releaseConnection();
}
} catch (final Exception e) {
LOGGER.logError("pdfReports", "error occured2 " + e.getMessage());
}
return null;
}
Included below part of code after 'client.executeMethod(method);' in 'pdfFile()' method and it works for me.
buf = new BufferedInputStream(method.getResponseBodyAsStream());
int readBytes = 0;
stream = getContext().getResponse().getOutputStream();
// write to the ServletOutputStream
while ((readBytes = buf.read()) != -1)
stream.write(readBytes);
I want to download image on click. I had set content type but I couldn't write image in response. In controller I get URL of image.
String image=myimageUrl;
File file = new File(image);
String contentType = getServletContext().getMimeType(file.getName());
response.setBufferSize(DEFAULT_BUFFER_SIZE);
response.setContentType(contentType);
response.setHeader("Content-Length", String.valueOf(file.length()));
For writing into response I used this code
DataInputStream input = new DataInputStream(new FileInputStream(file));
ServletOutputStream output = response.getOutputStream();
Here input returns null.
How to resolve this problem?
Please check following code.
for uploading image into database.
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
try {
String path=request.getParameter("h2");
out.println(path);
Connection connection=null;
ResultSet rs = null;
PreparedStatement psmnt = null;
FileInputStream fis;
Class.forName("com.mysql.jdbc.Driver");
connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/image", "root", "kshitij");
File image = new File(path);
psmnt = connection.prepareStatement("insert into new1(id,imagepath)"+"values(?,?)");
String s1=request.getParameter("h1");
psmnt.setString(1,s1);
fis = new FileInputStream(image);
psmnt.setBinaryStream(2, (InputStream)fis, (int)(image.length()));
int s = psmnt.executeUpdate();
if(s>0) {
out.println("Uploaded successfully !");
}
else {
out.println("unsucessfull to upload image.");
}
}
catch (Exception ex) {
System.out.println("Found some error : "+ex);
}
and for downloading image.
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
//response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
Connection connection = null;
ResultSet rs = null;
PreparedStatement psmnt = null;
InputStream sImage;
try {
Class.forName("com.mysql.jdbc.Driver").newInstance();
connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/image", "root", "kshitij");
psmnt = connection.prepareStatement("SELECT imagepath FROM new1 WHERE id = ?");
psmnt.setString(1, "23");
rs = psmnt.executeQuery();
if(rs.next()) {
byte[] bytearray = new byte[1048576];
int size=0;
sImage = rs.getBinaryStream(1);
//response.reset();
response.setContentType("image/jpeg");
while((size=sImage.read(bytearray))!= -1 ){
response.getOutputStream().write(bytearray,0,size);
}
}
}
catch(Exception ex){
// out.println("error :"+ex);
}
}