title: Rename file while uploading on webapp in spring using MultiPartFile datatype
body: <p>I have to upload an image from the user interface and change its name according to my need.</p>
  
  <p>i.e. if user uploads an image with a name WIN_20151122_09_57_47_Pro.jpg I would have to change it to 1.jpg</p>
  
  <p>I am using Spring mvc and for file upload and display I am  using <code>MultiPartFile</code> datatype</p>
  
  <p>Below is the model.</p>
  
  <pre><code>FileBucket.java
  
  package com.faisal.model;
  
  import org.springframework.web.multipart.MultipartFile ;
  
  public class FileBucket {
  
        MultipartFile file ;
  
         public MultipartFile getFile() {
               return file ;
        }
  
         public void setFile(MultipartFile file ) {
               this.file = file;
        }
  }
  </code></pre>
  
  <p>The controller part where I am uploading the file on the server</p>
  
  <pre><code>@Autowired
        ServletContext servletContext;
  
  @RequestMapping(value = "/singleUpload" , method = RequestMethod.POST)
         public String singleFileUpload(@Valid FileBucket fileBucket,
                    BindingResult result, ModelMap model ) throws IOException {
  
              String PROFILE_UPLOAD_LOCATION = servletContext.getRealPath("/" )
                          + File. separator + "resources" + File.separator
                          + "profile_images" + File.separator;
  
               if (result .hasErrors()) {
                    System. out.println("validation errors" );
                     return "singleFileUploader" ;
              } else {
                    System. out.println("Fetching file" );
                    String destination=PROFILE_UPLOAD_LOCATION
                                + fileBucket.getFile().getOriginalFilename();
  
                    File file = new File(destination);
                    File newFile=new File(PROFILE_UPLOAD_LOCATION +"1.jpg" );
  
  
                    FileCopyUtils. copy(fileBucket.getFile().getBytes(), file);
                    FileUtils. moveFile(file, newFile);
  
  
                    MultipartFile multipartFile = fileBucket .getFile();
                    String fileName = multipartFile .getOriginalFilename();
                     model.addAttribute("fileName" , fileName );
                     return "success" ;
              }
        }
  </code></pre>
  
  <p>View page</p>
  
  <pre><code>&lt;body&gt;
         &lt;div class="success" &gt;
  
         &lt;img src=" ${pageContext.request.contextPath}/resources/profile_images/${fileName} " height ="100" width="100" /&gt;
         &lt;br/&gt;
              File &lt;strong&gt; ${fileName}&lt;/strong &gt; uploaded successfully.
         &lt;/div&gt;
  
  &lt;/body&gt;
  </code></pre>
  
  <p>In the code above I have successfully renamed the file but then while redirecting on the same page the image is not displayed since it has been replaced by 1.jpg</p>