File upload in servlet corrupts the file

1k Views Asked by At

I am uploading a file using using (Valums uploader) and I using servlet at server side. File type is application/pdf. Code is :

String filename= request.getHeader("X-File-Name");
InputStream is = request.getInputStream();
File tmp = File.createTempFile(filename, "");
tmp.deleteOnExit();
FileOutputStream fos = new FileOutputStream(tmp);
IOUtils.copy(is, fos);
byte[] bytes = new byte[(int) tmp.length()];
is.read(bytes);

Now these bytes are getting stored into database as longblob. But it seems that inputStream in above code is adding some more data in the file thats why file data is getting corrupted. I download the same data as pdf file, found that both- original uploaded file and now downloaded file have the same size, but when the downloaded file is opened in Acrobat, it reports "File is corrupted". For upload request I have used only file input. So there are no chances of other input params in inputStream. Also the bytes array in above code are as it is passed for download. Why is data getting corrupted?

1

There are 1 best solutions below

1
On

Your problem might be the data length you are reading. I had similar problem and posted on this issue link Java: Binary File Upload using Restlet + Apache Commons FileUpload

Hope this helps