2

I am uploading a file using Servlet using the code as follows::

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);

What I am getting is my file is getting uploaded correctly. I needed to upload my file with different name, but make sure that file content should not be changed. Suppose I am having an image 'A.png' then it should be saved as 'B.png'. Please help guys?? I have tried like this:

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

fi.write(file);

But not working

Holger
  • 285,553
  • 42
  • 434
  • 765
androidGenX
  • 1,108
  • 3
  • 18
  • 44
  • use [`File#renameTo()`](http://docs.oracle.com/javase/7/docs/api/java/io/File.html#renameTo%28java.io.File%29) to rename a file. – Braj Oct 07 '14 at 11:11
  • @Braj can you Edit my code and paste as answer?? – androidGenX Oct 07 '14 at 11:11
  • @Braj in other examples they are creating new files and then saving, in those case it will loose the contents of my file, I need to keep my contents of page in there!! Contents must not be changed only name should be changes – androidGenX Oct 07 '14 at 11:16
  • first save the file on disk then just rename it. – Braj Oct 07 '14 at 11:17
  • fi.renameTo() method giving error!! – androidGenX Oct 07 '14 at 11:28
  • follow the Java Doc and the duplicate post for same code. How come we know that what error are you getting? – Braj Oct 07 '14 at 12:01
  • @Braj I tried like this File f1 = new File("Test"); // Rename file (or directory) file.renameTo(f1); fi.write(file); but not renaming. what should I do?? – androidGenX Oct 07 '14 at 12:36
  • Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/62596/discussion-between-androidgenx-and-braj). – androidGenX Oct 07 '14 at 12:38
  • First try with a plain standalone program. There is no need of `fi.write(file);` Just save the file then use the code mentioned [HERE](http://stackoverflow.com/questions/1158777/renaming-a-file-using-java?answertab=votes#tab-top) – Braj Oct 07 '14 at 12:39
  • @Holger but the issue is with file rename only. Change the file once uploaded file is saved on disk. As per OP *What I am getting is my file is getting uploaded correctly I am having an image 'A.png' then it should be saved as 'B.png'.* – Braj Oct 07 '14 at 13:12
  • @Holger FileItem fi = (FileItem) i.next(); – androidGenX Oct 07 '14 at 13:16
  • @Hogler I am using fileitem here to write into storage – androidGenX Oct 07 '14 at 13:21
  • @Holger I am uploading file as stream that is why i am using FileItem – androidGenX Oct 07 '14 at 13:31

2 Answers2

2

Assuming that you are referring to the Apache Commons FileItem you are simply in control what File instance you pass to FileItem.write. At that point, the File object is just an abstract name and the file will be created by that method.

It is your code which reads the name from the FileItem and constructs a File object with the same name. You don’t have to do it. So when you pass new File("B.png") to the write method of a FileItem representing an upload of A.png the contents will be save in a file B.png.


E.g. to do literally what you asked for you can change the line

fi.write(file);

to

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

A simplified version of your code may look like:

String fileName = fi.getName();// name provided by uploader
if (fileName == null || fileName == "") {
    resumefilepath = "";
} else {
    // convert to simple name, i.e. remove any prepended path
    fileName = fileName.substring(fileName.lastIndexOf(File.separatorChar)+1);
    // your substitution:
    if(fileName.equalsIgnoreCase("A.png")) fileName="B.png";
    // construct File object
    file = new File(resumePath, fileName);
    // and create/write the file
    fi.write(file);
}
Holger
  • 285,553
  • 42
  • 434
  • 765
  • @Hogler buddy yes I am using pache Commons FileItem. Can you tell how can I edit my code to do the same? I am not an expert like you. Please help me buddy – androidGenX Oct 07 '14 at 13:34
  • @Hogler buddy same issue its uploading but name not changing!! – androidGenX Oct 07 '14 at 14:05
  • Are you sure that the input name is `"A.png"`? You may add logging statements to find out what the actual values are. I’m quite confident that the `write` method will write to the file you specify and nothing else. You should also verify that you aren’t looking at an old file created by one of your previous attempts. – Holger Oct 07 '14 at 14:14
  • No buddy I am not!! I am sure, but dont know y it is nor renamed – androidGenX Oct 07 '14 at 14:19
0

If you are looking for an answer where you can upload file and change name and insert it into database here it is

<%
   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");


    }


    %>
Shubham Dixit
  • 9,242
  • 4
  • 27
  • 46