如何在Spring Boot中自定义文件上传目录

时间:2016-07-03 20:52:26

标签: spring spring-mvc spring-boot filesystems

我使用Spring Boot上传文件。目前,所有上传的文件都存储在" upload dir"目录。像这样:

public static String ROOT = "upload-dir";

上传方法如下所示(ROOT是文件存储的位置):

@RequestMapping(method = RequestMethod.POST, value = "/")
public String handleFileUpload(@RequestParam("file") MultipartFile file,
                               RedirectAttributes redirectAttributes) {

    if (!file.isEmpty()) { 
        try { 
            // Java NIO to copy the input stream to a local file
            Files.copy(file.getInputStream(), Paths.get(ROOT, file.getOriginalFilename()));
            redirectAttributes.addFlashAttribute("message",
                    "You successfully uploaded " + file.getOriginalFilename() + "!");
        } catch (IOException|RuntimeException e) {
            redirectAttributes.addFlashAttribute("message", "Failued to upload " + file.getOriginalFilename() + " => " + e.getMessage());
        }
    } else {
        redirectAttributes.addFlashAttribute("message", "Failed to upload " + file.getOriginalFilename() + " because it was empty");
    }

    return "redirect:/";
}

如何更改ROOT以便它询问用户特定的临时位置而不是加载应用程序的文件系统?

2 个答案:

答案 0 :(得分:0)

ROOT 更改为您想要的任何路径,例如' C:/ myphoto'

答案 1 :(得分:0)

我正在使用Spring Boot 1.5.16.RELEASE。

application.yml的配置:

spring:
  http:
    multipart:
      location: d:/root