服务器之家:专注于服务器技术及软件下载分享
分类导航

PHP教程|ASP.NET教程|Java教程|ASP教程|编程技术|正则表达式|C/C++|IOS|C#|Swift|Android|VB|R语言|JavaScript|易语言|vb.net|

服务器之家 - 编程语言 - Java教程 - SpringBoot 文件上传和下载的实现源码

SpringBoot 文件上传和下载的实现源码

2021-04-19 13:21dmfrm Java教程

这篇文章主要介绍了SpringBoot 文件上传和下载的实现源码,代码简单易懂非常不错,具有参考借鉴价值,需要的朋友可以参考下

本篇文章介绍springboot的上传和下载功能。

一、创建springboot工程,添加依赖

?
1
2
compile("org.springframework.boot:spring-boot-starter-web")
compile("org.springframework.boot:spring-boot-starter-thymeleaf")

工程目录为:

SpringBoot 文件上传和下载的实现源码

application.java 启动类

?
1
2
3
4
5
6
7
8
9
10
package hello;
import org.springframework.boot.springapplication;
import org.springframework.boot.autoconfigure.springbootapplication;
import org.springframework.boot.context.properties.enableconfigurationproperties;
@springbootapplication
public class application {
  public static void main(string[] args) {
    springapplication.run(application.class, args);
  }
}

二、创建测试页面

在resources/templates目录下新建uploadform.html

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
<html xmlns:th="http://www.thymeleaf.org">
<body>
  <div th:if="${message}">
    <h2 th:text="${message}"/>
  </div>
  <div>
    <form method="post" enctype="multipart/form-data" action="/">
      <table>
        <tr><td>file to upload:</td><td><input type="file" name="file" /></td></tr>
        <tr><td></td><td><input type="submit" value="upload" /></td></tr>
      </table>
    </form>
  </div>
  <div>
    <ul>
      <li th:each="file : ${files}">
        <a th:href="${file}" rel="external nofollow" th:text="${file}" />
      </li>
    </ul>
  </div>
</body>
</html>

三、新建storageservice服务

storageservice接口 

?
1
2
3
4
5
6
7
8
9
10
11
12
13
package hello.storage;
import org.springframework.core.io.resource;
import org.springframework.web.multipart.multipartfile;
import java.nio.file.path;
import java.util.stream.stream;
public interface storageservice {
  void init();
  void store(multipartfile file);
  stream<path> loadall();
  path load(string filename);
  resource loadasresource(string filename);
  void deleteall();
}

storageservice实现

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
package hello.storage;
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.util.stringutils;
import org.springframework.web.multipart.multipartfile;
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.nio.file.standardcopyoption;
import java.util.function.predicate;
import java.util.stream.stream;
@service
public class filesystemstorageservice implements storageservice
{
  private final path rootlocation = paths.get("upload-dir");
  /**
   * 保存文件
   *
   * @param file 文件
   */
  @override
  public void store(multipartfile file)
  {
    string filename = stringutils.cleanpath(file.getoriginalfilename());
    try
    {
      if (file.isempty())
      {
        throw new storageexception("failed to store empty file " + filename);
      }
      if (filename.contains(".."))
      {
        // this is a security check
        throw new storageexception("cannot store file with relative path outside current directory " + filename);
      }
      files.copy(file.getinputstream(), this.rootlocation.resolve(filename), standardcopyoption.replace_existing);
    }
    catch (ioexception e)
    {
      throw new storageexception("failed to store file " + filename, e);
    }
  }
  /**
   * 列出upload-dir下面所有文件
   * @return
   */
  @override
  public stream<path> loadall()
  {
    try
    {
      return files.walk(this.rootlocation, 1) //path -> !path.equals(this.rootlocation)
          .filter(new predicate<path>()
          {
            @override
            public boolean test(path path)
            {
              return !path.equals(rootlocation);
            }
          });
    }
    catch (ioexception e)
    {
      throw new storageexception("failed to read stored files", e);
    }
  }
  @override
  public path load(string filename)
  {
    return rootlocation.resolve(filename);
  }
  /**
   * 获取文件资源
   * @param filename 文件名
   * @return resource
   */
  @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);
    }
  }
  /**
   * 删除upload-dir目录所有文件
   */
  @override
  public void deleteall()
  {
    filesystemutils.deleterecursively(rootlocation.tofile());
  }
  /**
   * 初始化
   */
  @override
  public void init()
  {
    try
    {
      files.createdirectories(rootlocation);
    }
    catch (ioexception e)
    {
      throw new storageexception("could not initialize storage", e);
    }
  }
}

storageexception.java

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
package hello.storage;
public class storageexception extends runtimeexception {
  public storageexception(string message) {
    super(message);
  }
  public storageexception(string message, throwable cause) {
    super(message, cause);
  }
}
storagefilenotfoundexception.java
package hello.storage;
public class storagefilenotfoundexception extends storageexception {
  public storagefilenotfoundexception(string message) {
    super(message);
  }
  public storagefilenotfoundexception(string message, throwable cause) {
    super(message, cause);
  }
}

四、controller创建

将上传的文件,放到工程的upload-dir目录,默认在界面上列出可以下载的文件。

listuploadedfiles函数,会列出当前目录下的所有文件

servefile下载文件

handlefileupload上传文件

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
package hello; 
 
 
import java.io.ioexception;
import java.util.stream.collectors;
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.exceptionhandler;
import org.springframework.web.bind.annotation.getmapping;
import org.springframework.web.bind.annotation.pathvariable;
import org.springframework.web.bind.annotation.postmapping;
import org.springframework.web.bind.annotation.requestparam;
import org.springframework.web.bind.annotation.responsebody;
import org.springframework.web.multipart.multipartfile;
import org.springframework.web.servlet.mvc.method.annotation.mvcuricomponentsbuilder;
import org.springframework.web.servlet.mvc.support.redirectattributes;
import hello.storage.storagefilenotfoundexception;
import hello.storage.storageservice;
@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();
  }
}

源码下载:https://github.com/hellokittynii/springboot/tree/master/springbootuploadanddownload

总结

以上所述是小编给大家介绍的springboot 文件上传和下载的实现源码,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对服务器之家网站的支持!

原文链接:https://blog.csdn.net/u010889616/article/details/79764175
 

延伸 · 阅读

精彩推荐