上传时Java文件上传重命名文件

时间:2014-10-07 11:06:15

标签: java servlets file-upload

我使用Servlet使用Servlet上传文件,如下所示::

FileItem fi = (FileItem) i.next();
String fileName = fi.getName();
out.print("FileName: " + fileName);
String contentType = fi.getContentType();
boolean isInMemory = fi.isInMemory();
long sizeInBytes = fi.getSize();

if (fileName == null || fileName == "") {
    resumefilepath = "";
} else {

    resumeflag = 1;

    if (fileName.lastIndexOf("\\") >= 0) {

        file = new File(resumePath + fileName.substring(fileName.lastIndexOf("\\")));

    } else {

        file = new File(resumePath + fileName.substring(fileName.lastIndexOf("\\") + 1));

    }

    fi.write(file);

我得到的是我的文件正确上传。我需要使用不同的名称上传我的文件,但请确保不应更改文件内容。假设我有一个'A.png'图像,那么它应该保存为'B.png'。请帮帮忙?我试过这样的:

File f1 = new File("B.png");
// Rename file (or directory)
file.renameTo(f1);

fi.write(file);

但没有工作

2 个答案:

答案 0 :(得分:1)

假设您指的是Apache Commons FileItem,您可以控制传递给FileItem.writeFile个实例。此时,File对象只是一个抽象名称,该文件将由该方法创建。

您的代码从FileItem读取名称并构造具有相同名称的File对象。你不必这样做。因此,当您将new File("B.png")传递给代表上传write的{​​{1}} FileItem方法时,内容将保存在文件A.png中。


E.g。按字面意思做你所要求的就可以改变行

B.png

fi.write(file);

您的代码的简化版本可能如下所示:

if(file.getName().equals("A.png")) file=new File(file.getParentFile(), "B.png");
fi.write(file);

答案 1 :(得分:0)

如果您正在寻找答案,可以在此处上传文件并更改名称并将其插入数据库,则为

<%
   File file ;
   int maxFileSize = 5000 * 1024;
   int maxMemSize = 5000 * 1024;
   ServletContext context = pageContext.getServletContext();
   String filePath = "/NVS_upload/NVS_school_facilities_img/";
   String title=null,description=null,facility_id=null;
   ArrayList<String> imagepath=new ArrayList<String>();  
   String completeimagepath=null;

   // Verify the content type
   String contentType = request.getContentType();
   int verify=0;
   //String school_id=null;
   String exp_date=null;
   String rel_date=null;
   int school_id=0;
   String title_hindi=null;
   String description_hindi=null;

   if ((contentType.indexOf("multipart/form-data") >= 0)) {
      DiskFileItemFactory factory = new DiskFileItemFactory();
      // maximum size that will be stored in memory
      factory.setSizeThreshold(maxMemSize);

      // Location to save data that is larger than maxMemSize.
      factory.setRepository(new File("c:\\temp"));

      // Create a new file upload handler
      ServletFileUpload upload = new ServletFileUpload(factory);

      // maximum file size to be uploaded.
      upload.setSizeMax( maxFileSize );

      try { 
         // Parse the request to get file items.
         List fileItems = upload.parseRequest(request);

         // Process the uploaded file items
         Iterator i = fileItems.iterator();



         while ( i.hasNext () ) {
            FileItem fi = (FileItem)i.next();
            if ( !fi.isFormField () ) {
               // Get the uploaded file parameters
               String fieldName = fi.getFieldName();
               String fileName = fi.getName();
               boolean isInMemory = fi.isInMemory();
               long sizeInBytes = fi.getSize();
               //this genrates unique file name
               String id = UUID.randomUUID().toString();
               //we are splitting file name here such that we can get file name and extension differently
               String[] fileNameSplits = fileName.split("\\.");
              // extension is assumed to be the last part
               int extensionIndex = fileNameSplits.length - 1;
               // add extension to id
               String newfilename= id + "." + fileNameSplits[extensionIndex];
               //File newName = new File(filePath + "/" +);
               //this stores the new file name to arraylist so that it cn be stored in database
               imagepath.add(newfilename);  

               File uploadedFile = new File(filePath , newfilename);   
               fi.write(uploadedFile);


               out.println("Uploaded Filename: " + filePath + 
               newfilename + "<br>");
            }

            else if (fi.isFormField()) {


      if(fi.getFieldName().equals("title"))
        {   
          title=fi.getString();

          out.println(title);
        }


        if(fi.getFieldName().equals("description"))
        {   
             description=fi.getString();
             //out.println(description);
        }



        if(fi.getFieldName().equals("activity_name"))
        {   
             facility_id=fi.getString();
             //out.println(facility_id);
        }

if(fi.getFieldName().equals("rel_date"))
        {   
             rel_date=fi.getString();
             //out.println(school_id);
        }




        if(fi.getFieldName().equals("exp_date"))
        {   
             exp_date=fi.getString();
            // out.println(school_id);
        }


if(fi.getFieldName().equals("school_id"))
        {   
             school_id=Integer.valueOf(fi.getString());
            // out.println(school_id);
        }

if(fi.getFieldName().equals("title-hindi"))
        {   
             title_hindi=fi.getString();
            // out.println(school_id);
        }

if(fi.getFieldName().equals("description-hindi"))
        {   
            description_hindi=fi.getString();
             out.println(school_id);
        }

    }
         }
         out.println("</body>");
         out.println("</html>");
      } catch(Exception ex) {
         out.println(ex);
      }
   } 

   else {
      out.println("<html>");
      out.println("<head>");
      out.println("<title>Servlet upload</title>");  
      out.println("</head>");
      out.println("<body>");
      out.println("<p>No file uploaded</p>"); 
      out.println("</body>");
      out.println("</html>");
   }
%>

<%
try{


  completeimagepath=imagepath.get(0)+","+imagepath.get(1)+","+imagepath.get(2);


        Connection conn = null;
        Class.forName("org.postgresql.Driver").newInstance();
        conn = DriverManager.getConnection(
                "connection url");

PreparedStatement ps=conn.prepareStatement("INSERT INTO activities_upload (activity_name,title,description,pdfname,publish_date,expiry_date,title_hindi,description_hindi,school_id) VALUES(?,?,?,?,?,?,?,?,?)");
ps.setString(1,facility_id);
ps.setString(2,title);
ps.setString(3,description);
ps.setString(4,completeimagepath);
ps.setDate(5,java.sql.Date.valueOf(rel_date));
ps.setDate(6,java.sql.Date.valueOf(exp_date));
ps.setString(7,title_hindi);
ps.setString(8,description_hindi);
ps.setInt(9,school_id);

 verify=ps.executeUpdate();



        }

        catch(Exception e){
        out.println(e);

        }

    if(verify>0){
    HttpSession session = request.getSession(true);

    session.setAttribute("updated","true");
    response.sendRedirect("activitiesform.jsp");


    }


    %>