I have created the zip file (sample.zip) which has some files with no issues. When I open the sample.zip, it contains the file which expected.
I want to put that zip file into http response. Currently I am using the following:
response.setContentType("application/zip");
response.addHeader("Content-Disposition", "attachment; filename="+"sampleZip.zip");
response.setContentLength(2048);
response.setHeader("Set-Cookie", "fileDownload=true; path=/");
FileInputStream fileInputStream = new FileInputStream("sample.zip");
OutputStream responseOutputStream = response.getOutputStream();
int bytes;
while ((bytes = fileInputStream.read()) != -1) {
responseOutputStream.write(bytes);
}
response.flushBuffer();
Now its download the zip file in my browser default download location. But when I open that zip file it showing
Cannot open file: it does not appear to be valid archive
Kindly help me to fix this please.
This code looks good to me. But you are setting a default content length which might be the issue. Create File instanceand use the file.length() method to set the content length ans use the same file for your input stream. Also reading byte by byte is not a good idea. If possible use apache's IOUtils.copy() to copy data from your input stream to the ServletOutputStream.
Related
EDIT: The data I wanna send is in an rds. I fetch that into an output stream and then try to send it over as a pdf to the user.
The file gets generated but on opening the browser shows 'Failed to load PDF document.'
I have read that setting the ContentType to "application/pdf" helps but it does not in my case. The code is given below
byte[] b = generateFileService
.getDeviceHumidityRecordByPeriod(deviceIdValue, parseUnixTimestamp(startTime), parseUnixTimestamp(endTime));
OutputStream output = response.getOutputStream();
response.setContentType("application/pdf");
response.addHeader("Content-disposition", "attachment;filename=test.pdf");
output.write(b);
output.close();
response.flushBuffer();
}
if I change the file name to test.csv and then use content type as txt/plain, it works perfectly and a csv file is written.
I used Apache PDFBox to write data into a pdf file. The page offset needs to be tracked to add pages dynamically. Then you can convert the pdf into bytes and send it to the client by specifying response.setContentType("application/pdf") and response.addHeader("Content-disposition", "attachment;filename=test.pdf")
I am using java and struts. I have a scenario where there is 'Download' link in the page. After clicking on this link the control goes to the Action class, where I have String content which I need to write to a .txt file and then download that txt file.
Eventually whenever we click on the download link, we should be able to download a txt file having content a particular string.
I used below piece of code,
FileOutputStream outputStream = new FileOutputStream(fileNameWithDirectory);
outputStream.write(fileContentString.getBytes());
outputStream.close();
ActionForward forward = new ActionForward("doc/" + filename);
forward.setName(filename);
forward.setRedirect(true);
return forward;
Also I tried with FileWriter in place of FileOutputStream like,
FileWriter fileWriter = new FileWriter(fileNameWithDirectory);
fileWriter.write(fileContentString);
fileWriter.flush();
fileWriter.close();
But always instead of downloading the txt file, the control opens a new window where the String content is written.
Please suggest me, how would I able to download that .txt file.
You should add Content-Disposition: attachment to say browser, that it should download the file, not to open it.
See more details here
Also Struts has DownloadAction, you may use it as well.
You don't need to write the file and then redirect to it. You can set a http response header called Content-Disposition and then print your data into the http response body.
use it like this
response.addHeader("Content-Disposition", "Content-Disposition: attachment; filename=\""+filename+"\"");
of course this depends on which technology stack you're using.
Convert your text file to stream. and set content type as you wanted to download.
response.setContentType("application/pdf");
try {
// get your file as InputStream
InputStream is = ...;
// copy it to response's OutputStream
org.apache.commons.io.IOUtils.copy(is, convertedTextFiletoStream);
} catch (IOException ex) {
log.info("Error writing file to output stream. Filename was '{}'", fileName, ex);
throw new RuntimeException("IOError writing file to output stream");
}
String fileName="raj.doc";
ServletOutputStream stream=null;
BufferedInputStream buf=null;
stream=res.getOutputStream();
String s1=getServletContext().getRealPath("/web-inf/lib/raj.doc");
File doc=new File(s1);
res.setContentType("application/vnd.ms-word");
res.addHeader("Content-Disposition","attachment;filename= "+fileName);
res.setContentLength((int)doc.length());
FileInputStream input=new FileInputStream(doc);
buf=new BufferedInputStream(input);
int readBytes=0;
while((readBytes=buf.read())!=-1)
stream.write(readBytes);
Give me an example of downloading MS-word file in java. Tell me jar files which are needed.
You don't need any jars if you want to only download the file and not work with it.
Just use this code and replace the URL with the URL of your document. Then you should be able to create a new File and just feed everything you read from the URL in the outputstream of the file.
I have an InputStream which I would like to convert to a PDF, and save that PDF in a directory. Currently, my code is able to convert the InputStream to a PDF and the PDF does show up in the correct directory. However, when I try to open it, the file is damaged.
Here is the current code:
InputStream pAdESStream = signingServiceConnector.getDirectClient().getPAdES(this.statusReader.getStatusResponse().getpAdESUrl());
byte[] buffer = new byte[pAdESStream.available()];
pAdESStream.read(buffer);
File targetFile = new File(System.getProperty("user.dir") + "targetFile2.pdf");
OutputStream outStream = new FileOutputStream(targetFile);
outStream.write(buffer);
Originally, the InputStream was a pAdES-file (https://en.wikipedia.org/wiki/PAdES). However, it should be able to be read as just a regular PDF.
Does anyone know how to convert the InputStream to a PDF, without getting a damaged PDF as a result?
Hello it might be a bit late but you can use PDFBOX api (or itextpdf)
https://www.tutorialkart.com/pdfbox/create-write-text-pdf-file-using-pdfbox/
here is a tuto of the process gl
I am experiencing a strange behavior with java.util.zip.*
I have a zip file and upon decompressing follwing tihngs happen
ZipFile zipfile = new ZipFile(file, ZipFile.OPEN_READ);
This is exaxt error message
java.util.zip.ZipException: error in opening zip file
at java.util.zip.ZipFile.open(Native Method)
at java.util.zip.ZipFile.<init>(ZipFile.java:127)
at java.util.zip.ZipFile.<init>(ZipFile.java:143)
at com.basware.ExtractZip.unpack(ExtractZip.java:27)
at com.basware.ExtractZip.main(ExtractZip.java:17)
But if I use the following code it is able to open the archive without any errors
try {
BufferedOutputStream dest = null;
File file = new File("File_Path");
FileInputStream fis = new FileInputStream(file);
ZipInputStream zis = new ZipInputStream(new BufferedInputStream(fis));
ZipEntry entry;
while((entry = zis.getNextEntry()) != null) {
System.out.println("Extracting: " +entry);
int count;
byte data[] = new byte[BUFFER];
// write the files to the disk
FileOutputStream fos = new
FileOutputStream(entry.getName());
dest = new
BufferedOutputStream(fos, BUFFER);
while ((count = zis.read(data, 0, BUFFER))
!= -1) {
dest.write(data, 0, count);
}
dest.flush();
dest.close();
}
zis.close();
Please note that files are compressed using WinZIP.
My question is as ZipFile and ZipInputStream are almost same ,why ZipFile is giving exception and why it is unable to perform decompression.
EDIT : The problem is if I zip the file using WinZip tool and then decompress it using listed program it is working fine.But, this problem is specifically coming for archives coming from external source(external source claims that they are using WinZip).On top of it, if I open the very same archive(external one) using WinZip tool it is showing and decompressing files.But this JAVA specific code(ZipFile) is not working at all.
EDIT: I am not able to figure it out why java native code is not working for my ZIP archives, but apache compress solved my problem.It is working for me as suggested by Ian Roberts.
ZipFile attempts to parse the "central directory" at the end of the zip in order to build up a data structure that allows you to access individual entries by name. ZipInputStream doesn't, it only looks at the local header of each entry as it reads through the file from top to bottom. So it looks like your file has good entries but a corrupted central directory for some reason.
There are a number of possibilities, for example issues with the encoding of non-ASCII characters in entry names, or if the zip has more than 64k entries. I would try the commons-compress implementation of ZipFile - even if it doesn't work it should give you a more specific error message than the "something is wrong" that you get from java.util.zip.
In addition to Ian Robert's answer, if Java 7 is an option, you may wish to sidestep the older java.util.zip libraries in favor of using the ZIP filesystem provider.