0

My Servlet code is here

protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    Part image = request.getPart("pic");

    InputStream is =image.getInputStream();

    byte[] targetArray= new byte[is.available()];


    FileOutputStream fos = new FileOutputStream("F:\\image\\abc.jpg");
    fos.write(targetArray);
    is.close();
    fos.close();

}

This code is working and saved file size is same as uploaded file but when I open it,it is damaged,

  • The answer in the duplicate explains your mistake. This answer shows the correct way: http://stackoverflow.com/q/18664579 – BalusC Aug 02 '16 at 07:54

1 Answers1

0

Please try this code.

//add to your imports
import java.nio.file.*;

Part image = request.getPart("pic");
Path path = FileSystems.getDefault().getPath("F:/image", "abc.jpg");
try(InputStream is =image.getInputStream()){
    Files.copy(is, path);
}
rickz
  • 3,751
  • 2
  • 16
  • 24