2017-09-27 63 views
1

我正在使用spring boot 2.我的新任務是文件上傳。我已經做到了。但是我被要求在沒有向@RequestParam(「files」)MultipartFile文件[]等控制器方法中添加額外參數的情況下執行此操作。我想從請求中得到這個,而不是添加這個參數。使用Spring MVC進行文件上傳,但不在控制器方法中添加任何其他參數

我該如何解決這個問題?

我正在添加我目前的代碼。

@RequestMapping(value="/uploadMultipleFiles", method=RequestMethod.POST) 
    public @ResponseBody String handleFileUpload(@RequestParam("files") MultipartFile files[]){ 
      try { 
       String filePath="c:/temp/kk/"; 
       StringBuffer result=new StringBuffer(); 
       byte[] bytes=null; 
       result.append("Uploading of File(s) "); 

       for (int i=0;i<files.length;i++) { 
        if (!files[i].isEmpty()) { 
         bytes = files[i].getBytes(); 
         BufferedOutputStream stream = new BufferedOutputStream(new FileOutputStream(new File(filePath+files[i].getOriginalFilename()))); 
         stream.write(bytes); 
         stream.close(); 

         result.append(files[i].getOriginalFilename() + " Ok. ") ; 
        } 
        else 
         result.append(files[i].getOriginalFilename() + " Failed. "); 

      } 
       return result.toString(); 

      } catch (Exception e) { 
       return "Error Occured while uploading files." + " => " + e.getMessage(); 
      } 

    } 
+0

所以你想讓它更復雜而不是更簡單... –

回答

0

您可以從HttpRequest都有文件:

@RequestMapping(value="/uploadMultipleFiles", method=RequestMethod.POST) 
    public String handleFileUpload(HttpRequest request){ 

     MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request; 

     Map<String, MultipartFile> yourFiles = multipartRequest.getFileMap(); 

     return "All is Ok!"; 
    } 
0

我的示例代碼。

@RequestMapping(value = "/multiple/upload", method = RequestMethod.POST) 
public @ResponseBody String test(@RequestParam(value = "files[]") List<MultipartFile> files, 
     HttpServletRequest req) { 

    MultipartFileWriter writer = new MultipartFileWriter(); 
    String folderPath = "/file/"; 

    for (MultipartFile file : files) { 
     writer.writeFile(file, folderPath, req); 
    } 

    return "success"; 
} 
相關問題