2016-06-08 4 views
1

Я использую MultipartFile Spring Framework, чтобы дать пользователю возможность загрузить файл в формате PDF, и я хочу, чтобы сохранить файл в каталоге:загрузить файл и сохранить его в папку

Для этого я использую метод tranferTo() но это все еще не работает!

@RequestMapping(method = RequestMethod.POST, value = "/upload") 
    public CV handleFileUpload(@RequestParam("file") MultipartFile file) 
      throws IOException, SAXException, TikaException { 

    File convFile = new File(file.getOriginalFilename()); 
     System.out.println(file.getOriginalFilename()); 
      file.transferTo(convFile); 
} 

Как я могу добавить путь назначения?

ответ

2

Магазин в Каталина, которая является родительской папки в папку проекта

String rootPath = System.getProperty("catalina.home"); 
      File dir = new File(rootPath + File.separator + "yourfolderName"); 
      if (!dir.exists()) 
       dir.mkdirs(); 

      // Create the file on server 
      java.util.Date date= new java.util.Date(); 
      String Path = dir.getAbsolutePath() + File.separator + (new Timestamp(date.getTime())).toString().replace(":", "").toString().replace(".", ".").toString().replace(" ","").toString().replace("-","").toString()+".pdf"; 

Или магазин в определенной папке в проекте, такие как папка

@RequestMapping(value="/user/uploadFile", method=RequestMethod.POST) 
public ModelAndView handleFileUpload(ModelMap model,@RequestParam(value="file", required = false) MultipartFile file,HttpServletRequest request){ 

    if (!file.isEmpty()) { 
     //filter for checking file extewnsion 
     if(file.getContentType().equalsIgnoreCase("image/jpg") || file.getContentType().equalsIgnoreCase("image/jpeg")){ 
      //if file is >2 MB or < 2MB 
      double size = file.getSize(); 
      double kilobytes = (size/1024); 
      double megabytes = (kilobytes/1024); 
      if(megabytes<2){ 
     try { 
      byte[] bytes = file.getBytes(); 
      String filePath = request.getRealPath("/")+"yourFolderName\\ProfileImages\\"+SessionManagement.getUserName()+".jpg"; 
      BufferedOutputStream stream = 
        new BufferedOutputStream(new FileOutputStream(new File(filePath))); 
      stream.write(bytes); 
      stream.close(); 

      //console call 
     } 
     else{ 
      model.put("error", "Please select File less than 2 MB"); 
      return new ModelAndView("uploadPhotoTile"); 
     } 
     }else{ 
      model.put("error", "Please select JPEG File"); 
      return new ModelAndView("uploadPhotoTile"); 
     } 
    } else { 
     model.put("error", "Please select File"); 
     return new ModelAndView("uploadPhotoTile"); 
    } 
} 
Смежные вопросы