-1

I am uploading an image from c:\illuxplain on an android device. I have successfully uploaded the image but when I open it, it does not display.

Image size is non-zero in storage space and it displays extension .png. Why isn't the picture displaying? Is this right way to write file to storage space?

Windows Photo Viewer can't open this picture...

This is my servlet code

for (Part part : request.getParts()) {
    String fileName = extractFileName(part);
    File file = new File(fileSaveDir, fileName);
    InputStream input = part.getInputStream();

    byte[] buffer = new byte[1024];
    int len = input.read();

    FileOutputStream out = new FileOutputStream(file);
    while (len!=-1) {
        out.write(buffer,0,len);
        len = input.read(buffer);
    }
    out.close();
    input.close();
}
Barett
  • 5,826
  • 6
  • 51
  • 55
mubeen
  • 813
  • 2
  • 18
  • 39

2 Answers2

2

You are using the wrong read method in the following line:

int len = input.read();

This should be:

int len = input.read(buffer);
Andreas Veithen
  • 8,868
  • 3
  • 25
  • 28
1

Sample code:

byte data[] = new byte[1024];
long total = 0;
int count;


while ((count = input.read(data)) != -1) {
         total += count;
         output.write(data, 0, count);
}

output.flush();
output.close();
Ravindra babu
  • 37,698
  • 11
  • 250
  • 211