激情久久久_欧美视频区_成人av免费_不卡视频一二三区_欧美精品在欧美一区二区少妇_欧美一区二区三区的

服務器之家:專注于服務器技術及軟件下載分享
分類導航

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
 

延伸 · 閱讀

精彩推薦
主站蜘蛛池模板: 国产精品久久久久久婷婷天堂 | 中国洗澡偷拍在线播放 | 2017亚洲男人天堂 | 一级电影在线观看 | 91网站免费观看 | 91久久国产露脸精品国产 | 99爱视频在线观看 | 久久久国产精品成人免费 | 成人精品免费在线观看 | 97porn| 中文字幕综合 | 国产麻豆久久 | 欧美三日本三级少妇三级99观看视频 | 美国一级免费视频 | 理论片中文字幕 | 欧美福利视频一区二区 | 亚洲免费观看视频 | 青青草华人在线 | 免费毛片儿 | 亚洲一区二区国产 | 欧美精品成人一区二区三区四区 | 精品国产乱码久久久久久预案 | 毛片免费看的 | 黄色网络免费看 | 美国黄色毛片女人性生活片 | 黄网站免费观看视频 | 国语自产免费精品视频在 | 19禁国产精品福利视频 | 成人毛片视频在线播放 | 91短视频版高清在线观看www | 久久久免费 | 未成年人在线观看 | 国产成人免费高清激情视频 | 免费国产成人高清在线看软件 | 欧美1区2区在线观看 | 国产中出视频 | 午夜精品一区二区三区免费 | av手机免费在线观看 | 久久99精品久久久久久秒播蜜臀 | 成人黄色免费观看 | 国产中文av在线 |