Reputation: 401
I am writing download servlet that reads a html file and writes to servletOutputStream
, the problem right at the of the file transferred it is adding some garbage data any suggestions about this,
below is code I am using for this
int BUFFER_SIZE = 1024 * 8;
servOut = response.getOutputStream();
bos = new BufferedOutputStream(servOut);
fileObj = new File(file);
fileToDownload = new FileInputStream(fileObj);
bis = new BufferedInputStream(fileToDownload);
response.setContentType("application/text/html");
response.setHeader("ContentDisposition","attachment;filename="+dump+".html");
byte[] barray = new byte[BUFFER_SIZE];
while ((bis.read(barray, 0, BUFFER_SIZE)) != -1) {
bos.write(barray, 0, BUFFER_SIZE);
}
bos.flush();
Upvotes: 2
Views: 1488
Reputation: 500377
The problem is with the following part of your code:
while ((bis.read(barray, 0, BUFFER_SIZE)) != -1) {
bos.write(barray, 0, BUFFER_SIZE);
}
You are always writing out a multiple of BUFFER_SIZE
bytes, even if the size of your input isn't a multiple of BUFFER_SIZE
. This results in garbage being written at the end of the last block.
You can fix it like so:
int read;
while ((read = bis.read(barray, 0, BUFFER_SIZE)) != -1) {
bos.write(barray, 0, read);
}
Upvotes: 3
Reputation: 206719
bis.read
returns the number of bytes read. You need to take that into account in your write
call.
Something like:
int rd;
while ((rd=bis.read(...)) != -1) {
bos.write(..., rd);
}
Upvotes: 3