Issue
I made an upload file servlet, summed up like this:
ServletFileUpload upload = new ServletFileUpload();
FileItemIterator iter = upload.getItemIterator(request);
while (iter.hasNext()) {
FileItemStream item = iter.next();
InputStream stream = item.openStream()
File file = new File(path +"/"+ item.getFieldName));
FileOutputStream fout= new FileOutputStream (file);
BufferedOutputStream bout= new BufferedOutputStream (fout);
BufferedInputStream bin= new BufferedInputStream(stream);
byte buf[] = new byte[2048];
while ((bin.read(buf)) != -1){
bout.write(buf);
}
bout.close();
bin.close();
}
I used streams so that the file isn't loaded in memory.
The files are being uploaded smoothly, but I cannot open the resulted file (error differs depending on file type). Also the size of the resulted file is larger then the one of the original.
I tried different types of stream readers and writers but couldn't get any closer, and I couldn't find a similar problem. I ruled out encoding as I am receiving and writing bytes, so encoding doesn't matter, right?
What could be the problem?
Solution
You're writing all the content of buf array. This could be the problem for last read.
Change the while
loop like this:
int n;
while ((n = bin.read(buf)) != -1)
{
bout.write(buf, 0, n);
}
Answered By - Masud Parves Bhuiyan
Answer Checked By - Terry (JavaFixing Volunteer)