Upload File Vulnerability

1, when uploading pictures, some pictures may be the Trojan horse file, change the suffix extension of the picture. . . You need to determine the file stream, whether it is pictures

@WebServlet("/load/UploadServlet")
public class UploadServlet extends HttpServlet {

    /**
     * File Upload
     */
    protected void doPost(HttpServletRequest request, HttpServletResponse response) {
        String root = request.getServletContext().getRealPath("/upload");
        DiskFileItemFactory factory = new DiskFileItemFactory();
        ServletFileUpload upload = new ServletFileUpload(factory);
        try {
            List<FileItem> list = upload.parseRequest(request);
            for (FileItem it : list) {
                // 如果是file文件类型
                if (!it.isFormField()) {
                    // FileType fileType = getFileType(it.getInputStream());
                    // if (fileType == null) {
                    // // 非图片格式
                    // response.getWriter().write("fail");
                    // return;
                    // }
//                    String imgValue = fileType.getValue();
//                    System.out.println("imgValue:" + imgValue);
                    // 是图片格式
                    it.write(new File(root + "/" + it.getName()));
                    response.getWriter().write("success");

                }
            }
        } catch (Exception e) {
            try {
                response.getWriter().write("exception");
            } catch (IOException e1) {
                e1.printStackTrace ();
            }
            e.printStackTrace ();
        }
    }

    // whether a file is a picture format 
    public  static the FileType getFileType (the InputStream IS) throws IOException {
         byte [] the src = new new  byte [28 ];
        is.read(src, 0, 28);
        StringBuilder stringBuilder = new StringBuilder("");
        if (src == null || src.length <= 0) {
            return null;
        }
        for (int i = 0; i < src.length; i++) {
            int v = src[i] & 0xFF;
            String hv = Integer.toHexString(v).toUpperCase();
            if (hv.length() < 2) {
                stringBuilder.append(0);
            }
            stringBuilder.append(hv);
        }
        FileType[] fileTypes = FileType.values();
        for (FileType fileType : fileTypes) {
            if (stringBuilder.toString().startsWith(fileType.getValue())) {
                return fileType;
            }
        }
        return null;
    }

}

 

Guess you like

Origin www.cnblogs.com/pickKnow/p/11266743.html