一区二区三区在线-一区二区三区亚洲视频-一区二区三区亚洲-一区二区三区午夜-一区二区三区四区在线视频-一区二区三区四区在线免费观看

服務(wù)器之家:專注于服務(wù)器技術(shù)及軟件下載分享
分類導(dǎo)航

PHP教程|ASP.NET教程|Java教程|ASP教程|編程技術(shù)|正則表達(dá)式|C/C++|IOS|C#|Swift|Android|VB|R語言|JavaScript|易語言|vb.net|

服務(wù)器之家 - 編程語言 - Java教程 - SpringBoot 文件上傳和下載的實(shí)現(xiàn)源碼

SpringBoot 文件上傳和下載的實(shí)現(xiàn)源碼

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

這篇文章主要介紹了SpringBoot 文件上傳和下載的實(shí)現(xiàn)源碼,代碼簡單易懂非常不錯(cuò),具有參考借鑒價(jià)值,需要的朋友可以參考下

本篇文章介紹springboot的上傳和下載功能。

一、創(chuàng)建springboot工程,添加依賴

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

工程目錄為:

SpringBoot 文件上傳和下載的實(shí)現(xiàn)源碼

application.java 啟動(dòng)類

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

二、創(chuàng)建測試頁面

在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服務(wù)

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實(shí)現(xiàn)

?
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創(chuàng)建

將上傳的文件,放到工程的upload-dir目錄,默認(rèn)在界面上列出可以下載的文件。

listuploadedfiles函數(shù),會(huì)列出當(dāng)前目錄下的所有文件

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

總結(jié)

以上所述是小編給大家介紹的springboot 文件上傳和下載的實(shí)現(xiàn)源碼,希望對大家有所幫助,如果大家有任何疑問請給我留言,小編會(huì)及時(shí)回復(fù)大家的。在此也非常感謝大家對服務(wù)器之家網(wǎng)站的支持!

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

延伸 · 閱讀

精彩推薦
主站蜘蛛池模板: 美女黑人做受xxxxxⅹ | 国产一级视频久久 | 亚洲AV无码一区二区三区乱子伦 | 日本高清全集免费观看 | 福利一区三区 | 天天快乐在线观看 | 91在线老师啪国自产 | 动漫美女胸被狂揉扒开吃奶动态图 | 火影忍者小南裸羞羞漫画 | avtt天堂在线 | 男生的j桶女人屁免费视频 男生操男生 | 国产按摩系列 | 青青久久久国产线免观 | kisssis无减删全集在线观看 | 高清在线观看mv的网址免费 | 精品亚洲一区二区三区在线播放 | 91免费永久在线地址 | 99热免费在线观看 | 色美| haodiaose在线精品免费观看 | 青青草在线观看 | 亚洲国产精品综合一区在线 | 欧美透逼视频 | 免费观看日本人成影片 | 非洲一级毛片又粗又长aaaa | 高h生子双性美人受 | 美女全身体光羞羞漫画 | 国产一区二区免费不卡在线播放 | 男人叼女人的痛爽视频免费 | 国产一区二区视频在线 | 欧美一二区视频 | 免费视频网 | 精品国产综合 | 欧美最猛性xxxxx短视频 | japanesemoms乱熟| 精品免费国产一区二区三区 | 亚洲成人一区 | www.精品视频 | 羞羞答答免费人成黄页在线观看国产 | 日本中文字幕在线精品 | www久久久|