Spring MVC文件上传帮助

我一直在将spring集成到一个应用程序中,并且必须从表单重做文件上传。 我知道Spring MVC提供了什么以及我需要做些什么来配置我的控制器才能上传文件。 我已经阅读了足够的教程以便能够做到这一点,但这些教程没有解释的是关于如何/一旦你拥有文件后如何实际处理文件的正确/最佳实践方法。 下面是一些类似于Spring MVC Docs上关于处理文件上传的代码的代码,可以在这里找到
Spring MVC文件上传

在下面的示例中,您可以看到它们向您显示了获取文件的所有操作,但它们只是说使用bean做一些事情

我已经检查了很多教程,他们似乎都让我到了这一点,但我真正想知道的是处理文件的最佳方法。 此时我有一个文件,将此文件保存到服务器上的目录的最佳方法是什么? 有人可以帮我这个吗? 谢谢

public class FileUploadController extends SimpleFormController { protected ModelAndView onSubmit( HttpServletRequest request, HttpServletResponse response, Object command, BindException errors) throws ServletException, IOException { // cast the bean FileUploadBean bean = (FileUploadBean) command; let's see if there's content there byte[] file = bean.getFile(); if (file == null) { // hmm, that's strange, the user did not upload anything } //do something with the bean return super.onSubmit(request, response, command, errors); } 

这是我在上传时的偏好。我认为让spring处理文件保存是最好的方法。 Spring使用其MultipartFile.transferTo(File dest)函数来完成它。

 import java.io.File; import java.io.IOException; import javax.servlet.http.HttpServletResponse; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.multipart.MultipartFile; @Controller @RequestMapping("/upload") public class UploadController { @ResponseBody @RequestMapping(value = "/save") public String handleUpload( @RequestParam(value = "file", required = false) MultipartFile multipartFile, HttpServletResponse httpServletResponse) { String orgName = multipartFile.getOriginalFilename(); String filePath = "/my_uploads/" + orgName; File dest = new File(filePath); try { multipartFile.transferTo(dest); } catch (IllegalStateException e) { e.printStackTrace(); return "File uploaded failed:" + orgName; } catch (IOException e) { e.printStackTrace(); return "File uploaded failed:" + orgName; } return "File uploaded:" + orgName; } } 

但这些教程没有解释的是关于如何/一旦你拥有它来实际处理文件的正确/最佳实践方法

最佳实践取决于您要做的事情 。 通常我会使用一些AOP来处理上传的文件。 然后,您可以使用FileCopyUtils存储上传的文件

 @Autowired @Qualifier("commandRepository") private AbstractRepository commandRepository; protected ModelAndView onSubmit(...) throws ServletException, IOException { commandRepository.add(command); } 

AOP描述如下

 @Aspect public class UploadedFileAspect { @After("execution(* br.com.ar.CommandRepository*.add(..))") public void storeUploadedFile(JoinPoint joinPoint) { Command command = (Command) joinPoint.getArgs()[0]; byte[] fileAsByte = command.getFile(); if (fileAsByte != null) { try { FileCopyUtils.copy(fileAsByte, new File("")); } catch (IOException e) { /** * log errors */ } } } 

不要忘记启用方面(如果需要,将模式更新到Spring 3.0)放上类路径aspectjrt.jar和aspectjweaver.jar( / lib / aspectj)和

    

使用以下控制器类处理文件上载。

 @Controller public class FileUploadController { @Autowired private FileUploadService uploadService; @RequestMapping(value = "/fileUploader", method = RequestMethod.GET) public String home() { return "fileUploader"; } @RequestMapping(value = "/upload", method = RequestMethod.POST) public @ResponseBody List upload(MultipartHttpServletRequest request, HttpServletResponse response) throws IOException { // Getting uploaded files from the request object Map fileMap = request.getFileMap(); // Maintain a list to send back the files info. to the client side List uploadedFiles = new ArrayList(); // Iterate through the map for (MultipartFile multipartFile : fileMap.values()) { // Save the file to local disk saveFileToLocalDisk(multipartFile); UploadedFile fileInfo = getUploadedFileInfo(multipartFile); // Save the file info to database fileInfo = saveFileToDatabase(fileInfo); // adding the file info to the list uploadedFiles.add(fileInfo); } return uploadedFiles; } @RequestMapping(value = {"/listFiles"}) public String listBooks(Map map) { map.put("fileList", uploadService.listFiles()); return "listFiles"; } @RequestMapping(value = "/getdata/{fileId}", method = RequestMethod.GET) public void getFile(HttpServletResponse response, @PathVariable Long fileId) { UploadedFile dataFile = uploadService.getFile(fileId); File file = new File(dataFile.getLocation(), dataFile.getName()); try { response.setContentType(dataFile.getType()); response.setHeader("Content-disposition", "attachment; filename=\"" + dataFile.getName() + "\""); FileCopyUtils.copy(FileUtils.readFileToByteArray(file), response.getOutputStream()); } catch (IOException e) { e.printStackTrace(); } } private void saveFileToLocalDisk(MultipartFile multipartFile) throws IOException, FileNotFoundException { String outputFileName = getOutputFilename(multipartFile); FileCopyUtils.copy(multipartFile.getBytes(), new FileOutputStream(outputFileName)); } private UploadedFile saveFileToDatabase(UploadedFile uploadedFile) { return uploadService.saveFile(uploadedFile); } private String getOutputFilename(MultipartFile multipartFile) { return getDestinationLocation() + multipartFile.getOriginalFilename(); } private UploadedFile getUploadedFileInfo(MultipartFile multipartFile) throws IOException { UploadedFile fileInfo = new UploadedFile(); fileInfo.setName(multipartFile.getOriginalFilename()); fileInfo.setSize(multipartFile.getSize()); fileInfo.setType(multipartFile.getContentType()); fileInfo.setLocation(getDestinationLocation()); return fileInfo; } private String getDestinationLocation() { return "Drive:/uploaded-files/"; } }