在Java Servlet中使用commons fileupload写入新文件之前,覆盖所有内容

时间:2019-04-11 12:24:28

标签: java apache servlets apache-commons-fileupload

在上载到路径之前,我不知道如何覆盖目录中的同名文件。

Java:

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

    User objUser = (User) request.getSession().getAttribute("UserConnected");
        int user_idConnected = objUser.getUser_id();

    try {
        ServletFileUpload sf = new ServletFileUpload(new DiskFileItemFactory());
        List<FileItem> multiFile = sf.parseRequest(request);

        for (FileItem item : multiFile) {
            String w = item.getName();
            int length = w.length();
            String ext = w.substring(w.length() - 4);
            String n = "user"+user_idConnected+ext;
            String destDir = "C:\\Users\\pm\\Desktop\\NETBEANS\\snfe\\web\\img\\users\\"; 
            item.write(new File(destDir+n));
            UserService objUserService = new UserService();
            objUserService.updateIdFile(n, user_idConnected);
        }

        System.out.println("file uploaded");
        response.sendRedirect("profile#recove");
    } catch (Exception e) {
        System.out.println(e);
        HttpSession sesion=request.getSession();
        String done = "Error, try again.";
        sesion.setAttribute("done", done);
        response.sendRedirect("profile?done=false");
    }
}

0 个答案:

没有答案