上传文件中的目录优化-打散

来源:互联网 发布:强制视频软件破解版 编辑:程序博客网 时间:2024/06/11 20:18

思想:

 

核心代码:

publicclass Up2Servletextends HttpServlet {

 

    public void doPost(HttpServletRequest request, HttpServletResponse response)

           throws ServletException,IOException {

        request.setCharacterEncoding("UTF-8");

        Stringpath = getServletContext().getRealPath("/up");// path is:D:\workspace\.metadata\.plugins\org.eclipse.wst.server.core\tmp0\wtpwebapps\0514\up

        DiskFileItemFactorydisk = newDiskFileItemFactory();//声明临时文件

        ServletFileUploadsfu = newServletFileUpload(disk);//声明解析request的核心类

 

        // 声明一个Map用于传递参数

        Map<String,Object> img = newHashMap<String, Object>();

        try {

           List<FileItem>files = sfu.parseRequest(request);//解析request

           FileItemfile = files.get(0);

           String fileName = file.getName();// 获取文件名fileName is:F:\娱乐\\f.jpg

 

           fileName= fileName.substring(fileName.lastIndexOf("\\") + 1);

           img.put("oldname",fileName);

           // 获取扩展名

           StringexName = fileName.substring(fileName.lastIndexOf("."));

           Stringuuid = UUID.randomUUID().toString().replace("-","");

           StringnewName = uuid + exName;// 新名字

 

           //计算文件夹名

           int hashCode =uuid.hashCode();

           Stringdir1 = Integer.toHexString(hashCode & 0xff);

           Stringdir2 = Integer.toHexString((hashCode >> 8) & 0xff);

           // 组成目录

           String relPath = path + "/" + dir1 +"/" + dir2;   //relPathis:D:\workspace\.metadata\.plugins\org.eclipse.wst.server.core\tmp0\wtpwebapps\0514\up/96/65 注意写路径时up会不小心丢失,96/65是随机生成

           // 判断目录是否存在

           Filef = newFile(relPath);

           if (!f.exists()) {

               f.mkdirs();

           }

           FileUtils.copyInputStreamToFile(file.getInputStream(),newFile(f,newName));

           // 去显示

           request.setAttribute("fileName","/"+ dir1 +"/"+ dir2 + "/"

                  +newName);

           request.getRequestDispatcher("/jsps/show.jsp").forward(request,

                  response);

           img.put("newname",dir1 +"/"+ dir2 + "/"+ newName);

           img.put("ip",request.getRemoteAddr());

        }catch(Exception e) {

           e.printStackTrace();

        }

    }

}

 

 

 

原创粉丝点击