欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

基于SpringBoot上传任意文件功能的实现

程序员文章站 2024-02-15 09:21:16
一、pom文件依赖的添加 o...

一、pom文件依赖的添加

<dependencies>
    <dependency>
      <groupid>org.springframework.boot</groupid>
      <artifactid>spring-boot-starter-web</artifactid>
    </dependency>

    <dependency>
      <groupid>org.springframework.boot</groupid>
      <artifactid>spring-boot-starter-test</artifactid>
      <scope>test</scope>
    </dependency>

    <dependency>
      <groupid>org.springframework.boot</groupid>
      <artifactid>spring-boot-starter-thymeleaf</artifactid>
    </dependency>
  </dependencies>

二、controller层

@controller
public class fileuploadcontroller {
  private final storageservice storageservice;

  @autowired
  public fileuploadcontroller(storageservice storageservice) {
    this.storageservice = storageservice;
  }

  //展示上传过的文件
  @getmapping("/")
  public string listuploadedfiles(model model) throws ioexception {

    model.addattribute("files", storageservice.loadall().map(path ->
            mvcuricomponentsbuilder.frommethodname(fileuploadcontroller.class, "servefile", path.getfilename().tostring())
            .build().tostring())
        .collect(collectors.tolist()));

    return "uploadform";
  }

  //下载选定的上传的文件
  @getmapping("/files/{filename:.+}")
  @responsebody
  public responseentity<resource> servefile(@pathvariable string filename) {

    resource file = storageservice.loadasresource(filename);
    return responseentity
        .ok()
        .header(httpheaders.content_disposition, "attachment; filename=\""+file.getfilename()+"\"")
        .body(file);
  }

  //上传文件
  @postmapping("/")
  public string handlefileupload(@requestparam("file") multipartfile file,
                  redirectattributes redirectattributes) {

    storageservice.store(file);
    redirectattributes.addflashattribute("message",
        "you successfully uploaded " + file.getoriginalfilename() + "!");

    return "redirect:/";
  }

  @exceptionhandler(storagefilenotfoundexception.class)
  public responseentity<?> handlestoragefilenotfound(storagefilenotfoundexception exc) {
    return responseentity.notfound().build();
  }
}

三、实现的service层

@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() {
    filesystemutils.deleterecursively(rootlocation.tofile());
  }

  @override
  public void init() {
    try {
      files.createdirectory(rootlocation);
    } catch (ioexception e) {
      throw new storageexception("could not initialize storage", e);
    }
  }
}

四、在application.properties文件上配置上传的属性

spring.http.multipart.max-file-size=128kb
spring.http.multipart.max-request-size=128kb

五、服务启动时的处理

基于SpringBoot上传任意文件功能的实现

六、测试成功的结果

基于SpringBoot上传任意文件功能的实现

以上这篇基于springboot上传任意文件功能的实现就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持。