Spring Boot Webapplication文件上载(.war)

Spring Boot Webapplication文件上载(.war),spring,tomcat,spring-boot,upload,war,Spring,Tomcat,Spring Boot,Upload,War,我有个问题。我做了一个小的申请,以获得在春季开机。 我添加了一个文件上传功能,该功能适用于我的.jar。现在,我想在Tomcat8上部署应用程序,但文件上传不再起作用。 我想问题是上传文件夹的目录 这: @GetMapping("/uploadForm") public String listUploadedFiles(Model model) throws IOException { model.addAttribute("files", fileSystemStor

我有个问题。我做了一个小的申请,以获得在春季开机。 我添加了一个文件上传功能,该功能适用于我的.jar。现在,我想在Tomcat8上部署应用程序,但文件上传不再起作用。 我想问题是上传文件夹的目录

这:

@GetMapping("/uploadForm")
      public String listUploadedFiles(Model model) throws IOException {

      model.addAttribute("files", fileSystemStorageService.loadAll().map(
          path -> MvcUriComponentsBuilder.fromMethodName(FileUploadController.class,
              "serveFile", path.getFileName().toString()).build().toString())
          .collect(Collectors.toList()));
这似乎就是问题所在。在.jar文件中,可以找到upload dir文件夹。 但我不知道如何把它变成一场战争。 Spring Boot在战争中需要上传文件夹的地方

谢谢你

这里有更多的信息

这是我的Stacktrace:

hello.storage.StorageException: Failed to read stored files
at hello.storage.FileSystemStorageService.loadAll(FileSystemStorageService.java:50) ~[FileSystemStorageService.class:?]
at hello.controller.FileUploadController.listUploadedFiles(FileUploadController.java:33) ~[FileUploadController.class:?]
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[?:1.8.0_111]
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[?:1.8.0_111]
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[?:1.8.0_111]
at java.lang.reflect.Method.invoke(Method.java:498) ~[?:1.8.0_111]
at org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:205) ~[spring-web-4.3.10.RELEASE.jar:4.3.10.RELEASE]
at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:133) ~[spring-web-4.3.10.RELEASE.jar:4.3.10.RELEASE]
at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:97) ~[spring-webmvc-4.3.10.RELEASE.jar:4.3.10.RELEASE]
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:827) ~[spring-webmvc-4.3.10.RELEASE.jar:4.3.10.RELEASE]
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:738) ~[spring-webmvc-4.3.10.RELEASE.jar:4.3.10.RELEASE]
at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:85) ~[spring-webmvc-4.3.10.RELEASE.jar:4.3.10.RELEASE]
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:967) ~[spring-webmvc-4.3.10.RELEASE.jar:4.3.10.RELEASE]
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:901) ~[spring-webmvc-4.3.10.RELEASE.jar:4.3.10.RELEASE]
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:970) ~[spring-webmvc-4.3.10.RELEASE.jar:4.3.10.RELEASE]
at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:861) ~[spring-webmvc-4.3.10.RELEASE.jar:4.3.10.RELEASE]
at javax.servlet.http.HttpServlet.service(HttpServlet.java:622) ~[servlet-api.jar:?]
at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:846) ~[spring-webmvc-4.3.10.RELEASE.jar:4.3.10.RELEASE]
at javax.servlet.http.HttpServlet.service(HttpServlet.java:729) ~[servlet-api.jar:?]
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:291) ~[catalina.jar:8.0.23]
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206) ~[catalina.jar:8.0.23]
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52) ~[tomcat-websocket.jar:8.0.23]
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:239) ~[catalina.jar:8.0.23]
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206) ~[catalina.jar:8.0.23]
at org.springframework.web.filter.RequestContextFilter.doFilterInternal(RequestContextFilter.java:99) ~[spring-web-4.3.10.RELEASE.jar:4.3.10.RELEASE]
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) ~[spring-web-4.3.10.RELEASE.jar:4.3.10.RELEASE]
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:239) ~[catalina.jar:8.0.23]
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206) ~[catalina.jar:8.0.23]
at org.springframework.web.filter.HttpPutFormContentFilter.doFilterInternal(HttpPutFormContentFilter.java:105) ~[spring-web-4.3.10.RELEASE.jar:4.3.10.RELEASE]
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) ~[spring-web-4.3.10.RELEASE.jar:4.3.10.RELEASE]
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:239) ~[catalina.jar:8.0.23]
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206) ~[catalina.jar:8.0.23]
at org.springframework.web.filter.HiddenHttpMethodFilter.doFilterInternal(HiddenHttpMethodFilter.java:81) ~[spring-web-4.3.10.RELEASE.jar:4.3.10.RELEASE]
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) ~[spring-web-4.3.10.RELEASE.jar:4.3.10.RELEASE]
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:239) ~[catalina.jar:8.0.23]
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206) ~[catalina.jar:8.0.23]
at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:197) ~[spring-web-4.3.10.RELEASE.jar:4.3.10.RELEASE]
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) ~[spring-web-4.3.10.RELEASE.jar:4.3.10.RELEASE]
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:239) ~[catalina.jar:8.0.23]
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206) ~[catalina.jar:8.0.23]
at org.springframework.boot.web.support.ErrorPageFilter.doFilter(ErrorPageFilter.java:115) [spring-boot-1.5.6.RELEASE.jar:1.5.6.RELEASE]
at org.springframework.boot.web.support.ErrorPageFilter.access$000(ErrorPageFilter.java:59) [spring-boot-1.5.6.RELEASE.jar:1.5.6.RELEASE]
at org.springframework.boot.web.support.ErrorPageFilter$1.doFilterInternal(ErrorPageFilter.java:90) [spring-boot-1.5.6.RELEASE.jar:1.5.6.RELEASE]
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) [spring-web-4.3.10.RELEASE.jar:4.3.10.RELEASE]
at org.springframework.boot.web.support.ErrorPageFilter.doFilter(ErrorPageFilter.java:108) [spring-boot-1.5.6.RELEASE.jar:1.5.6.RELEASE]
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:239) [catalina.jar:8.0.23]
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206) [catalina.jar:8.0.23]
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:219) [catalina.jar:8.0.23]
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:106) [catalina.jar:8.0.23]
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:502) [catalina.jar:8.0.23]
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:142) [catalina.jar:8.0.23]
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:79) [catalina.jar:8.0.23]
at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:617) [catalina.jar:8.0.23]
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:88) [catalina.jar:8.0.23]
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:518) [catalina.jar:8.0.23]
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1091) [tomcat-coyote.jar:8.0.23]
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:668) [tomcat-coyote.jar:8.0.23]
at org.apache.tomcat.util.net.AprEndpoint$SocketProcessor.doRun(AprEndpoint.java:2463) [tomcat-coyote.jar:8.0.23]
at org.apache.tomcat.util.net.AprEndpoint$SocketProcessor.run(AprEndpoint.java:2452) [tomcat-coyote.jar:8.0.23]
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142) [?:1.8.0_111]
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617) [?:1.8.0_111]
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61) [tomcat-util.jar:8.0.23]
at java.lang.Thread.run(Thread.java:745) [?:1.8.0_111]
Caused by: java.nio.file.NoSuchFileException: src\upload-dir
at sun.nio.fs.WindowsException.translateToIOException(WindowsException.java:79) ~[?:1.8.0_111]
at sun.nio.fs.WindowsException.rethrowAsIOException(WindowsException.java:97) ~[?:1.8.0_111]
at sun.nio.fs.WindowsException.rethrowAsIOException(WindowsException.java:102) ~[?:1.8.0_111]
at sun.nio.fs.WindowsFileAttributeViews$Basic.readAttributes(WindowsFileAttributeViews.java:53) ~[?:1.8.0_111]
at sun.nio.fs.WindowsFileAttributeViews$Basic.readAttributes(WindowsFileAttributeViews.java:38) ~[?:1.8.0_111]
at sun.nio.fs.WindowsFileSystemProvider.readAttributes(WindowsFileSystemProvider.java:193) ~[?:1.8.0_111]
at java.nio.file.Files.readAttributes(Files.java:1737) ~[?:1.8.0_111]
at java.nio.file.FileTreeWalker.getAttributes(FileTreeWalker.java:219) ~[?:1.8.0_111]
at java.nio.file.FileTreeWalker.visit(FileTreeWalker.java:276) ~[?:1.8.0_111]
at java.nio.file.FileTreeWalker.walk(FileTreeWalker.java:322) ~[?:1.8.0_111]
at java.nio.file.FileTreeIterator.<init>(FileTreeIterator.java:72) ~[?:1.8.0_111]
at java.nio.file.Files.walk(Files.java:3574) ~[?:1.8.0_111]
at hello.storage.FileSystemStorageService.loadAll(FileSystemStorageService.java:    46) ~[FileSystemStorageService.class:?]
... 62 more
这是我的文件系统存储服务

package hello.storage;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.Resource;
import org.springframework.core.io.UrlResource;
import org.springframework.stereotype.Service;
import org.springframework.util.FileSystemUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.net.MalformedURLException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Stream;

@Service
public class FileSystemStorageService implements StorageService {

  private final Path rootLocation;

  @Autowired
  public FileSystemStorageService(StorageProperties properties) {

    this.rootLocation = Paths.get(properties.getLocation());
  }

  @Override
  public void store(MultipartFile file) {
    try {
      if (file.isEmpty()) {
        throw new StorageException("Failed to store empty file " + file.getOriginalFilename());
      }
      Files.copy(file.getInputStream(), this.rootLocation.resolve(file.getOriginalFilename()));
    } catch (IOException e) {
      throw new StorageException("Failed to store file " + file.getOriginalFilename(), e);
    }
  }

  @Override
  public Stream<Path> loadAll() {
    try {
      return Files.walk(this.rootLocation, 1)
          .filter(path -> !path.equals(this.rootLocation))
          .map(path -> this.rootLocation.relativize(path));
    } catch (IOException e) {
      throw new StorageException("Failed to read stored files", e);
    }

  }

  @Override
  public Path load(String filename) {
    return rootLocation.resolve(filename);
  }

  @Override
  public Resource loadAsResource(String filename) {
    try {
      Path file = load(filename);
      Resource resource = new UrlResource(file.toUri());
      if(resource.exists() || resource.isReadable()) {
        return resource;
      }
      else {
        throw new StorageFileNotFoundException("Could not read file: " + filename);

      }
    } catch (MalformedURLException e) {
      throw new StorageFileNotFoundException("Could not read file: " + filename, e);
    }
  }

  @Override
  public void deleteAll() {

    List<File> files = Arrays.asList(rootLocation.toFile().listFiles());
    for (File file:files) {
      FileSystemUtils.deleteRecursively(file);
    }


  }

  @Override
public void init() {
  try {
    Files.createDirectory(rootLocation);
  } catch (IOException e) {
    throw new StorageException("Could not initialize storage", e);
  }
}
}
这是我的StorageFileNotFoundException

package hello.storage;

public class StorageFileNotFoundException extends StorageException {
  public StorageFileNotFoundException(String message) {
    super(message);
  }

  public StorageFileNotFoundException(String message, Throwable cause) {

    super(message, cause);
  }
}
这是我的FileUploadController

package hello.controller;

import hello.storage.FileSystemStorageService;
import hello.storage.StorageFileNotFoundException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.Resource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.method.annotation.MvcUriComponentsBuilder;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import java.io.IOException;
import java.util.stream.Collectors;

@Controller
public class FileUploadController {
  private final FileSystemStorageService fileSystemStorageService;


    @Autowired
    public FileUploadController (FileSystemStorageService fileSystemStorageService) {
      this.fileSystemStorageService = fileSystemStorageService;
    }

    @GetMapping("/uploadForm")
      public String listUploadedFiles(Model model) throws IOException {


      model.addAttribute("files", fileSystemStorageService.loadAll().map(
          path -> MvcUriComponentsBuilder.fromMethodName(FileUploadController.class,
              "serveFile", path.getFileName().toString()).build().toString())
          .collect(Collectors.toList()));

      if (model.asMap().size() > 0) {
        return "uploadForm";
      }
      return null;
    }


    @GetMapping("/files/{filename:.+}")
    @ResponseBody
    public ResponseEntity<Resource> serveFile(@PathVariable String filename){

    Resource file = fileSystemStorageService.loadAsResource(filename);
    return ResponseEntity.ok().header(HttpHeaders.CONTENT_DISPOSITION,
        "attachment;filename=\"" + file.getFilename() + "\"").body(file);
    }

    @PostMapping("/uploadForm")
      public String handleFileUpload (@RequestParam("file")MultipartFile file,
          RedirectAttributes redirectAttributes)  {

      try{
      fileSystemStorageService.store(file);
//      redirectAttributes.addFlashAttribute("message", "You successfully uploaded " + file.getOriginalFilename() + "!");

      }
      catch (Exception exc){
        exc.printStackTrace();
      }

      return "redirect:/uploadForm";
      }


    @RequestMapping("/delete")
      public String deleteAllFiles (){
        fileSystemStorageService.deleteAll();

      return "redirect:/uploadForm";

    }

      @ExceptionHandler(StorageFileNotFoundException.class)
  public ResponseEntity<?> handleStorageFileNotFound(StorageFileNotFoundException exc){
        return ResponseEntity.notFound().build();
      }
}
包hello.controller;
导入hello.storage.FileSystemStorageService;
导入hello.storage.StorageFileNotFoundException;
导入org.springframework.beans.factory.annotation.Autowired;
导入org.springframework.core.io.Resource;
导入org.springframework.http.HttpHeaders;
导入org.springframework.http.ResponseEntity;
导入org.springframework.stereotype.Controller;
导入org.springframework.ui.Model;
导入org.springframework.web.bind.annotation.*;
导入org.springframework.web.multipart.MultipartFile;
导入org.springframework.web.servlet.mvc.method.annotation.MvcUriComponentsBuilder;
导入org.springframework.web.servlet.mvc.support.RedirectAttributes;
导入java.io.IOException;
导入java.util.stream.collector;
@控制器
公共类FileUploadController{
专用最终文件系统存储服务文件系统存储服务;
@自动连线
公共文件上载控制器(文件系统存储服务文件系统存储服务){
this.fileSystemStorageService=fileSystemStorageService;
}
@GetMapping(“/uploadForm”)
公共字符串listUploadedFiles(模型)引发IOException{
model.addAttribute(“文件”,fileSystemStorageService.loadAll().map(
路径->MvcUriComponentsBuilder.fromMethodName(FileUploadController.class,
“serveFile”,path.getFileName().toString()).build().toString())
.collect(Collectors.toList());
如果(model.asMap().size()>0){
返回“上传表单”;
}
返回null;
}
@GetMapping(“/files/{filename:.+}”)
@应答器
公共响应属性服务文件(@PathVariable字符串文件名){
Resource file=fileSystemStorageService.loadAsResource(文件名);
返回ResponseEntity.ok().header(HttpHeaders.CONTENT\u),
“附件;文件名=\”“+文件.getFilename()+”\).body(文件);
}
@后映射(“/uploadForm”)
公共字符串handleFileUpload(@RequestParam(“文件”)多部分文件,
重定向属性(重定向属性){
试一试{
fileSystemStorageService.store(文件);
//redirectAttributes.addFlashAttribute(“消息”,“您已成功上载”+文件.getOriginalFilename()+“!”);
}
捕获(异常exc){
exc.printStackTrace();
}
返回“重定向:/uploadForm”;
}
@请求映射(“/delete”)
公共字符串deleteAllFiles(){
fileSystemStorageService.deleteAll();
返回“重定向:/uploadForm”;
}
@ExceptionHandler(StorageFileNotFoundException.class)
公共响应handleStorageFileNotFound(StorageFileNotFoundException exc){
返回ResponseEntity.notFound().build();
}
}

我是这么说的,它可以与.jar打包一起使用,但是如果我在Tomcat上使用它作为.war…

你能更新你的war文件目录结构吗?你得到了什么错误,有日志吗?我们需要更多信息请你更新你的war文件目录结构吗?你得到了什么错误,有日志吗?我们需要更多信息
package hello.storage;

public class StorageFileNotFoundException extends StorageException {
  public StorageFileNotFoundException(String message) {
    super(message);
  }

  public StorageFileNotFoundException(String message, Throwable cause) {

    super(message, cause);
  }
}
package hello.controller;

import hello.storage.FileSystemStorageService;
import hello.storage.StorageFileNotFoundException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.Resource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.method.annotation.MvcUriComponentsBuilder;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import java.io.IOException;
import java.util.stream.Collectors;

@Controller
public class FileUploadController {
  private final FileSystemStorageService fileSystemStorageService;


    @Autowired
    public FileUploadController (FileSystemStorageService fileSystemStorageService) {
      this.fileSystemStorageService = fileSystemStorageService;
    }

    @GetMapping("/uploadForm")
      public String listUploadedFiles(Model model) throws IOException {


      model.addAttribute("files", fileSystemStorageService.loadAll().map(
          path -> MvcUriComponentsBuilder.fromMethodName(FileUploadController.class,
              "serveFile", path.getFileName().toString()).build().toString())
          .collect(Collectors.toList()));

      if (model.asMap().size() > 0) {
        return "uploadForm";
      }
      return null;
    }


    @GetMapping("/files/{filename:.+}")
    @ResponseBody
    public ResponseEntity<Resource> serveFile(@PathVariable String filename){

    Resource file = fileSystemStorageService.loadAsResource(filename);
    return ResponseEntity.ok().header(HttpHeaders.CONTENT_DISPOSITION,
        "attachment;filename=\"" + file.getFilename() + "\"").body(file);
    }

    @PostMapping("/uploadForm")
      public String handleFileUpload (@RequestParam("file")MultipartFile file,
          RedirectAttributes redirectAttributes)  {

      try{
      fileSystemStorageService.store(file);
//      redirectAttributes.addFlashAttribute("message", "You successfully uploaded " + file.getOriginalFilename() + "!");

      }
      catch (Exception exc){
        exc.printStackTrace();
      }

      return "redirect:/uploadForm";
      }


    @RequestMapping("/delete")
      public String deleteAllFiles (){
        fileSystemStorageService.deleteAll();

      return "redirect:/uploadForm";

    }

      @ExceptionHandler(StorageFileNotFoundException.class)
  public ResponseEntity<?> handleStorageFileNotFound(StorageFileNotFoundException exc){
        return ResponseEntity.notFound().build();
      }
}