Spring MVC文件上传帮助


问题内容

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


在下面的示例中,您可以看到他们向您展示了获取文件的所有操作,但是他们只是说了 “用豆做某事”。

我检查了许多教程,它们似乎都使我明白了这一点,但是我真正想知道的是处理文件的最佳方法。一旦有了文件,将文件保存到服务器目录的最佳方法是什么?有人可以帮我吗?谢谢

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;
    }
}