servlet3.0 getPart()与getParts()获取上传文件

需求: servlet3.0以上,就是tomcat7.0以上,web.xml->web-app->version 3.0以上, 不需要引入其它的jar包

Servlet类需要添加注释@MultipartConfig, 必要, 否则request.getPart()会为null


@MultipartConfig
public class FileServlet extends HttpServlet {
    
    public void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        SimpleDateFormat format = new SimpleDateFormat("yyyyMMddHHmmssSSS");
        //文件存放目录
        String mypath = this.getClass().getClassLoader().getResource("/../../").getPath() + "upload";
        File file = new File(mypath );
        if(!file.exists()){
            file.mkdir();
        }
        String filename = format.format(new Date());
        // multipart/form-data 
        if (ServletFileUpload.isMultipartContent(request)) {
            Part part = request.getPart("ff");
            if(part == null){
                return;
            }

            String headerfNValue = part.getHeader("content-disposition");
            if("".equals(headerfNValue.trim()){
                return ;
            }

            //headerfNValue = [filename="xxxx.xxx"]
            String valueKey = "filename=\"";
            int s = headerfNValue.indexOf(valueKey );
            if(s < 0){
                return;
            }

            String originalfilename = headerfNValue.substring(s + valueKey.length(), headerfNValue.length()-1);
;
            String suffix =  originalfilename.substring(originalfilename.lastIndexOf("."));
            if(".jpg|.jpeg|.jpe|.jfif|.png|.gif|.bmp|.dib|.tif|.tiff".indexOf(suffix) < 0){
                 return;
            }
            
            filename += suffix;
        
            InputStream input = part.getInputStream();
        
            file = new File(mypath + filename);
            if(!file.exists()){
                file.createNewFile();
            }
        
            FileOutputStream fos = new FileOutputStream(file);

            int size = 0;
            byte[] buffer = new byte[1024];
            while ((size = input.read(buffer)) != -1) {
                fos.write(buffer, 0, size);
            }
            fos.close();
            input.close(); 
        }
    }
}


getParts() 就是多个Part ,for出来就可以
关于 @MultipartConfig 注释:
@MultipartConfig(location = "/upload", maxFileSize = 1024 * 1024 * 50)
设置了location 就是文件的保存路径 , 确认Part的filename不为空后,可以直接写入, 可以省去后面的文件流操作
......
filename += suffix;
part.write(filename);


前端页面:





你可能感兴趣的:(JAVA)