Java Spring MVC 文件上传帮助

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3577942/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-14 02:03:26  来源:igfitidea点击:

Spring MVC File Upload Help

javaspringfile-uploadspring-mvc

提问by TheJediCowboy

I have been integrating spring into an application, and have to redo a file upload from forms. I am aware of what Spring MVC has to offer and what I need to do to configure my controllers to be able to upload files. I have read enough tutorials to be able to do this, but what none of these tutorials explain is correct/best practice methods on how/what is to be done to actually handle the file once you have it. Below is some code similar to code found on the Spring MVC Docs on handling file uploads which can be found at
Spring MVC File Upload

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

In the example below you can see that they show you everything to do to get the file, but they just say Do Something with the bean

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

I have checked many tutorials and they all seem to get me to this point, but what I really want to know is the best way to handle the file. Once I have a file at this point, what is the best way to save this file to a directory on a server? Can somebody please help me with this? Thanks

我查看了许多教程,它们似乎都让我走到了这一步,但我真正想知道的是处理文件的最佳方法。一旦我有了一个文件,将这个文件保存到服务器上的目录的最佳方法是什么?有人可以帮我解决这个问题吗?谢谢

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

采纳答案by Ferid Gürbüz

This is what i prefer while making uploads.I think letting spring to handle file saving, is the best way. Spring does it with its MultipartFile.transferTo(File dest)function.

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

回答by Arthur Ronald

but what none of these tutorials explain is correct/best practice methods on how/what is to be done to actually handle the file once you have it

但是这些教程都没有解释正确/最佳实践方法,即一旦您拥有文件,如何/如何实际处理该文件

The best practice depends on what you are trying to do. Usually i use some AOP to post-proccessing the uploaded file. Then you can use FileCopyUtilsto store your uploaded file

最佳实践取决于您要尝试做什么。通常我使用一些 AOP 对上传的文件进行后期处理。然后你可以使用FileCopyUtils来存储你上传的文件

@Autowired
@Qualifier("commandRepository")
private AbstractRepository<Command, Integer> commandRepository;

protected ModelAndView onSubmit(...) throws ServletException, IOException {
    commandRepository.add(command);
}

AOP is described as follows

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
                  */
            }
        }

    }

Do not forget enable aspect (update schema to Spring 3.0 if needed) Put on the classpath aspectjrt.jar and aspectjweaver.jar (<SPRING_HOME>/lib/aspectj) and

不要忘记启用方面(如果需要,将架构更新到 Spring 3.0)放在类路径 aspectjrt.jar 和 aspectjweaver.jar (<SPRING_HOME>/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"/>

回答by donjos

Use the below controller class for processing the file upload.

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

@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/";
  }
}