androidGenX
androidGenX

Reputation: 1148

Java file upload rename file on uploading

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

Upvotes: 2

Views: 11004

Answers (2)

Shubham Dixit
Shubham Dixit

Reputation: 1

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


    }


    %>

Upvotes: 0

Holger
Holger

Reputation: 298143

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

Upvotes: 2

Related Questions