0

I am try uploading the image using the below servlet But after upload I am able save the file but I am not able to open I checked the file is corrupted.

Instead of using the annotation I have describe multipart-config in web.xml. I this code I am trying to get the image file I send the data using AJAX. Then I am redirected to Register servlet there I am using InputStream class to handle data. After this I creating the file and upload this Inputdata to file in some directory on server.

public class Register extends HttpServlet{
    @Override 
    protected void doPost(HttpServletRequest req,HttpServletResponse res) throws ServletException,IOException{
        String username=req.getParameter("username");
        String password=req.getParameter("password");
        String email=req.getParameter("email");
        Part part = req.getPart("image");
        String filename = part.getSubmittedFileName();
        InputStream is = req.getInputStream();
        byte[] data = new byte[is.available()];
        String path = "D:\\FullstackWeb\\images\\icon\\"+filename;
        System.out.println(path);
        FileOutputStream fos=new FileOutputStream(path);
        fos.write(data);
        res.setContentType("text/html");
        PrintWriter out = res.getWriter();
        try {
            Class.forName("com.mysql.jdbc.Driver");
            Connection conn = DriverManager.getConnection("jdbc:mysql://dns1.nishchay.com:3306/register","demouser","123Nbr@");
            String query = "Insert INTO register.signup(username,email,userpassword,filename) values(? ,?, ?,?)";
            PreparedStatement pstmt= conn.prepareStatement(query);
            pstmt.setString(1, username);
            pstmt.setString(2, email);
            pstmt.setString(3, password);
            pstmt.setString(4, path);       
            pstmt.executeUpdate();      
            conn.close();
        }catch(Exception e) {
            out.println("<h1>Issue is occured</h1>");       
        }       
    }
}```


nischit
  • 1
  • 1

1 Answers1

0

You are not reading in the image data:

    InputStream is = req.getInputStream();
    byte[] data = new byte[is.available()];
    String path = "D:\\FullstackWeb\\images\\icon\\"+filename;
    System.out.println(path);
    FileOutputStream fos=new FileOutputStream(path);
    fos.write(data);

does not contain any is.read() call and it doesn't close the FileOutputStream.

In addition to that your allocated buffer is to small for most images. The JavaDoc for InputStream.available() states

Returns an estimate of the number of bytes that can be read (or skipped over) from this input stream without blocking

To completely read the image data you could simply replace the above code with

Files.copy(is, Paths.get("D:\\FullstackWeb\\images\\icon\\"+filename));

but with a big caveat: since the file name is supplied by the user of your service this opens your code to security problems.

Thomas Kläger
  • 17,754
  • 3
  • 23
  • 34
  • Thanks Thomas for the earlier explanation. It working well with Files.copy method. I just start learning the servlet. Please could you help me understand the below point @ since the file name is supplied by the user of your service this opens your code to security problems. Also is there any way to limit the size for file upload by user ? – nischit Nov 26 '21 at 03:44
  • @nischit about the size limit see https://stackoverflow.com/questions/28564683/how-to-limit-uploaded-filesize-in-tomcat-servlet – Thomas Kläger Nov 26 '21 at 14:44
  • @nischit about the possible security problem: what `part.getSubmittedFileName()` returns depends entirely upon whatever the user of your servlet is sending. A malicious attacker could send `"..\\..\\index.html"` as submitted filename and your code would blindly overwrite `D:\FullstackWeb\index.html`. There are several things to take into consideration that don't fit into this small space. I'd suggest you search for "path traversal" and "directory traversal" to get an idea of the problem. – Thomas Kläger Nov 26 '21 at 14:52
  • Thank you Thomas pointing out this problem. – nischit Nov 27 '21 at 06:26