Home Spring rest upload file is corrupted
Reply: 1

Spring rest upload file is corrupted

Pavan Jois
1#
Pavan Jois Published in 2018-01-12 11:54:17Z

I have a java application which uses spring rest to upload a jar file.
But the uploaded file is corrupted and I am not able to access the jar file from the server.
Please help.

fileloc = fileloc.replace("$", "/");
String filename = uploadedFileRef.getOriginalFilename();
String path = fileloc + filename;
byte[] buffer = new byte[1000];
File outputFile = new File(path);
FileInputStream reader = null;
FileOutputStream writer = null;
int totalBytes = 0;
try {
  outputFile.createNewFile();
  reader = (FileInputStream) uploadedFileRef.getInputStream();
  writer = new FileOutputStream(outputFile);
  int bytesRead = 0;
  while ((bytesRead = reader.read(buffer)) != -1) {
    writer.write(buffer);
    totalBytes += bytesRead;
  }
} catch (IOException e) {
  e.printStackTrace();
} finally {
  try {
    reader.close();
    writer.close();
  } catch (IOException e) {
    e.printStackTrace();
  }
}
StanislavL
2#
StanislavL Reply to 2018-01-12 12:47:16Z

You call

writer.write(buffer);

so you write always the buffer size. Imagine the last read reads 10 bytes only but you will write 1000 bytes anyway.

Use

write(buffer, 0, bytesRead );

Or just check the question

You need to login account before you can post.

About| Privacy statement| Terms of Service| Advertising| Contact us| Help| Sitemap|
Processed in 0.342756 second(s) , Gzip On .

© 2016 Powered by mzan.com design MATCHINFO