Spring MVC文件上传帮助

时间:2010-08-26 17:50:06

标签: java spring file-upload spring-mvc

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

在下面的示例中,您可以看到他们向您展示了获取文件的所有操作,但他们只是说使用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);
}

3 个答案:

答案 0 :(得分:20)

这是我在上传时的偏好。我认为让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;
    }
}

答案 1 :(得分:2)

  

但是这些教程没有解释的是正确/最佳实践方法,了解如何/一旦有文件后如何实际处理文件

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

@Autowired
@Qualifier("commandRepository")
private AbstractRepository<Command, Integer> 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("<SET_UP_TARGET_FILE_RIGHT_HERE>"));
            } catch (IOException e) {
                /**
                  * log errors
                  */
            }
        }

    }

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

<beans xmlns="http://www.springframework.org/schema/beans"
      xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
      xmlns:aop="http://www.springframework.org/schema/aop"
      xsi:schemaLocation="http://www.springframework.org/schema/beans
                          http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
                          http://www.springframework.org/schema/aop
                          http://www.springframework.org/schema/aop/spring-aop-2.5.xsd">
    <aop:aspectj-autoproxy />
    <bean class="br.com.ar.aop.UploadedFileAspect"/>

答案 2 :(得分:-1)

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

@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<UploadedFile> upload(MultipartHttpServletRequest request, HttpServletResponse response) throws IOException {

    // Getting uploaded files from the request object
    Map<String, MultipartFile> fileMap = request.getFileMap();

    // Maintain a list to send back the files info. to the client side
    List<UploadedFile> uploadedFiles = new ArrayList<UploadedFile>();

    // 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<String, Object> 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/";
  }
}
相关问题