I am trying to download excel (.xlsx) file by using following code - java

File getting downloaded successfully but I cannot open file, it seems to be corrupted.Not sure what I am missing.
public StreamingResponseBody getStreamingFile() throws IOException {
response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
response.setHeader("Content-Disposition", "attachment; filename=\"discrepancyReport.xls\"");
InputStream inputStream = new FileInputStream(new File(rootPath + ".xlsx"));
return outputStream -> {
int nRead;
byte[] data = new byte[4096];
while ((nRead = inputStream.read(data, 0, data.length)) != -1) {
outputStream.write(data, 0, nRead);
}
inputStream.close();
};

Issue seems to be with swagger.When I tried hitting end-point directly, It is working as expected.

Related

getOutputStream() has already been called for this response for ServletOutputStream outputStream = response.getOutputStream();

Getting exception as getOutputStream() has already been called for this response when using
ServletOutputStream outputStream = response.getOutputStream();
in my code.
Here is the sample code. First i'm placing the input file in my local path which is a svg image. After that svg is converted into png and get downloaded from browser.
{ //code to write image into local path
File filesvg = new File(inFile);
svg = svg.replace("1e-006","0.000001");
FileWriter writer = new FileWriter(filesvg);
writer.write(svg);
writer.close();
//here some lines of code to convert to png
return outFile;
}
//Code to download image from browser.
response.setContentType("application/octet-stream");
response.setHeader("Content-Disposition",
"attachment;filename=\"" + filename + ext + "\"");
FileInputStream fileIn = new FileInputStream(file);
ServletOutputStream outputStream =
response.getOutputStream();
byte[] outputByte = new byte[4096];
int byteRead;
while ((byteRead = fileIn.read(outputByte, 0, 4096))
!= -1) {
outputStream.write(outputByte, 0, byteRead);
}
fileIn.close();
outputStream.flush();
outputStream.close();

Download link to CSV file in the mail using spring boot

I am generating csv in my code, It takes some time to generate. So, I am sending an email with link once the csv file is generated. When I click that, getting 404 not found error. When I have the same link in the html, I am able to download it. Any insight or sample to refer
Sample Link -http://localhost:9090/api/report/file?fileName=filename.csv
Java code to download the report
#RequestMapping(value = "api/report/file")
public void downloadCSV(HttpServletResponse response, #RequestParam("fileName") String fileName) throws IOException {
File file = new File(fileName);
InputStream is = new FileInputStream(file);
response.setContentType("application/octet-stream");
// Response header
response.setHeader("Content-Disposition", "attachment; filename=\"" + file.getName() + "\"");
// Read from the file and write into the response
OutputStream os = response.getOutputStream();
byte[] buffer = new byte[1024];
int len;
while ((len = is.read(buffer)) != -1) {
os.write(buffer, 0, len);
}
os.flush();
os.close();
is.close();
}
Add GET method to this mapping: #RequestMapping(value = "api/report/file")

Servlet writing file contains binary at the end

I have a servlet to let user download a file from server. The original file is human readable, but the downloaded file alwyas contains binary content at the end of the file.
HttpSession session = request.getSession(true);
String fileName = session.getAttribute("download").toString();
System.out.println("Download file " + fileName);
File file = new File(fileName);
FileInputStream fileIn = new FileInputStream(file);
response.setContentType("text/plain");
response.setHeader("Content-Disposition", "attachment;filename=" + file.getName());
ServletOutputStream out = response.getOutputStream();
byte[] bytes = new byte[BYTES_DOWNLOAD];
while (fileIn.read(bytes, 0, BYTES_DOWNLOAD) != -1) {
out.write(bytes, 0, BYTES_DOWNLOAD);
}
out.flush();
out.close();
Thanks in advance.
Small bug in your code:
byte[] bytes = new byte[BYTES_DOWNLOAD];
int count;
while ( (count = fileIn.read(bytes)) != -1) {
out.write(bytes, 0, count);
}
What binary content do you see? Is it perhaps the line endings in the file, if any?

Copying a file.Finding a path to it

I want to copy file to another directory.I know this has been asked million times,I read tons of answers about this but I just can't seem to make it work.This is the code I am currently using:
copyFile(new File(getClass().getResource("/jars/TurnOffClient.jar").toString()),
new File("C:\\Documents and Settings\\All Users\\Start Menu\\Programs\\Startup\\karioc.jar"));
And this is the method:
public static void copyFile(File sourceFile, File destFile) throws IOException {
if(!destFile.exists()) {
destFile.createNewFile();
}
FileChannel source = null;
FileChannel destination = null;
try {
source = new FileInputStream(sourceFile).getChannel();
destination = new FileOutputStream(destFile).getChannel();
destination.transferFrom(source, 0, source.size());
}
finally {
if(source != null) {
source.close();
}
if(destination != null) {
destination.close();
}
}
}
This is my dir:
Directories http://imageshack.com/a/img820/6418/5g3m.png
//////////////////////////////////////////////////////////////////////////////////////////
And this is the exception I get:
Standard ways to copy a file don't work because you are trying to copy the file out of the JAR. When you get a file out of a JAR, you can't get a File object for it. You can get a URL, and from that an InputStream.
An existing answer includes code to copy data from one input stream to another. Here it is, adapted for the file inside a JAR:
InputStream in = getClass().getResourceAsStream("/jars/TurnOffClient.jar");
OutputStream out = new FileOutputStream(new File("C:\\Documents and Settings\\All Users\\Start Menu\\Programs\\Startup\\karioc.jar"));
// Transfer bytes from in to out
byte[] buf = new byte[1024];
int len;
while ((len = in.read(buf)) != -1) {
out.write(buf, 0, len);
}
in.close();
out.close();
Have you tried using java.nio.Files.copy(); ?
There's built in methods for doing this.
If that doesn't work then go ahead and transfer bytes from a file inputstream to an output file stream.
public void copy(File src, File dst) throws IOException {
InputStream in = new FileInputStream(src);
OutputStream out = new FileOutputStream(dst);
// Transfer bytes from in to out
byte[] buf = new byte[1024];
int len;
while ((len = in.read(buf)) > 0) {
out.write(buf, 0, len);
}
in.close();
out.close();
}
As described here: Standard concise way to copy a file in Java?

How to compress and download a xlsx file using zip in java

I'm creating a xlsx using poi and saving it on fileSystem. I need to download the file on a servlet call and due to memory constraints I did not create a xssf workbook object and used the following code instead :
byte[] buf = new byte[1024];
ServletOutputStream sOut = response.getOutputStream();
FileInputStream input = null;
try {
long length = fileToRead.length();
input = new FileInputStream(fileToRead);
while ((input != null) && ((length = input.read(buf)) != -1)) {
sOut.write(buf, 0, (int) length);
}
Where fileToRead is the file present at the file system.
How can I integrate this with How to create a zip file in Java
You could use
ZipOutputStream zos = new ZipOutputStream(response.getOutputStream());
....
ze = new ZipEntry("xlsData");
zos.putEntry (ze);
// loop
zos.write(buf, 0, (int) length);
// finally
zos.close();

Categories

Resources