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

服務(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教程 - 基于Spring實現(xiàn)文件上傳功能

基于Spring實現(xiàn)文件上傳功能

2020-12-24 12:01MrQin Java教程

這篇文章主要為大家詳細(xì)介紹了Spring實現(xiàn)文件上傳功能,具有一定的參考價值,感興趣的小伙伴們可以參考一下

本小節(jié)你將建立一個可以接受HTTP multi-part 文件的服務(wù)。

你將建立一個后臺服務(wù)來接收文件以及前臺頁面來上傳文件。

要利用servlet容器上傳文件,你要注冊一個MultipartConfigElement類,以往需要在web.xml 中配置<multipart-config>,
而在這里,你要感謝SpringBoot,一切都為你自動配置好了。

1、新建一個文件上傳的Controller:

應(yīng)用已經(jīng)包含一些 存儲文件 和 從磁盤中加載文件 的類,他們在cn.tiny77.guide05這個包下。我們將會在FileUploadController中用到這些類。

?
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
package cn.tiny77.guide05;
 
import java.io.IOException;
import java.util.List;
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;
 
@Controller
public class FileUploadController {
 
 private final StorageService storageService;
 
 @Autowired
 public FileUploadController(StorageService storageService) {
  this.storageService = storageService;
 }
 
 @GetMapping("/")
 public String listUploadedFiles(Model model) throws IOException {
  
  List<String> paths = storageService.loadAll().map(
    path -> MvcUriComponentsBuilder.fromMethodName(FileUploadController.class,
      "serveFile", path.getFileName().toString()).build().toString())
    .collect(Collectors.toList());
 
  model.addAttribute("files", paths);
 
  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();
 }
 
}

該類用@Controller注解,因此SpringMvc可以基于它設(shè)定相應(yīng)的路由。每一個@GetMapping和@PostMapping注解將綁定對應(yīng)的請求參數(shù)和請求類型到特定的方法。

GET / 通過StorageService 掃描文件列表并 將他們加載到 Thymeleaf 模板中。它通過MvcUriComponentsBuilder來生成資源文件的連接地址。

GET /files/{filename} 當(dāng)文件存在時候,將加載文件,并發(fā)送文件到瀏覽器端。通過設(shè)置返回頭"Content-Disposition"來實現(xiàn)文件的下載。

POST / 接受multi-part文件并將它交給StorageService保存起來。

你需要提供一個服務(wù)接口StorageService來幫助Controller操作存儲層。接口大致如下

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
package cn.tiny77.guide05;
 
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();
 
}

以下是接口實現(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
package cn.tiny77.guide05;
 
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.stream.Stream;
 
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.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;
 
@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) {
  String filename = StringUtils.cleanPath(file.getOriginalFilename());
  try {
   if (file.isEmpty()) {
    throw new StorageException("無法保存空文件 " + filename);
   }
   if (filename.contains("..")) {
    // This is a security check
    throw new StorageException(
      "無權(quán)訪問該位置 "
        + filename);
   }
   Files.copy(file.getInputStream(), this.rootLocation.resolve(filename),
     StandardCopyOption.REPLACE_EXISTING);
  }
  catch (IOException e) {
   throw new StorageException("無法保存文件 " + filename, 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("讀取文件異常", 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(
      "無法讀取文件: " + filename);
 
   }
  }
  catch (MalformedURLException e) {
   throw new StorageFileNotFoundException("無法讀取文件: " + filename, e);
  }
 }
 
 @Override
 public void deleteAll() {
  FileSystemUtils.deleteRecursively(rootLocation.toFile());
 }
 
 @Override
 public void init() {
  try {
   Files.createDirectories(rootLocation);
  }
  catch (IOException e) {
   throw new StorageException("初始化存儲空間出錯", e);
  }
 }
}

2、建立一個Html頁面

這里使用Thymeleaf模板

?
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
<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>

頁面主要分為三部分分

- 頂部展示SpringMvc傳過來的信息
- 一個提供用戶上傳文件的表單
- 一個后臺提供的文件列表

3、限制上傳文件的大小

在文件上傳的應(yīng)用中通常要設(shè)置文件大小的,想象一下后臺處理的文件如果是5GB,那得多糟糕!在SpringBoot中,我們可以通過屬性文件來控制。
新建一個application.properties,代碼如下:
spring.http.multipart.max-file-size=128KB #文件總大小不能超過128kb
spring.http.multipart.max-request-size=128KB #請求數(shù)據(jù)的大小不能超過128kb

4、應(yīng)用啟動函數(shù)

?
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
package cn.tiny77.guide05;
 
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
 
 
@SpringBootApplication
@EnableConfigurationProperties(StorageProperties.class)
public class Application {
 
 public static void main(String[] args) {
  SpringApplication.run(Application.class, args);
 }
 
 @Bean
 CommandLineRunner init(StorageService storageService) {
  return (args) -> {
   storageService.deleteAll();
   storageService.init();
  };
 }
}

5、運行結(jié)果

基于Spring實現(xiàn)文件上傳功能

以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持服務(wù)器之家。

原文鏈接:http://www.cnblogs.com/qins/p/7461464.html

延伸 · 閱讀

精彩推薦
主站蜘蛛池模板: 日本强不卡在线观看 | 碰91精品国产91久久婷婷 | 好大好硬抽搐好爽想要 | 好大水好多好爽好硬好深视频 | 1769在线视频 | 亚洲国产精品自产在线播放 | 亚洲欧美日韩国产精品影院 | 精品一区二区三区在线视频观看 | 天天乐影院 | 国产卡一卡二卡三卡四 | 免费观看全集 | 四虎精品免费视频 | 亚洲精品久久久992KVTV | 大团圆免费阅读全文 | chinese国产人妖videos | 国产免费不卡视频 | 国产精品久久久久久久久99热 | 无码人妻精品一区二区蜜桃在线看 | 国产不卡视频一区二区在线观看 | 欧美午夜视频一区二区三区 | 亚洲精品视频免费在线观看 | avtt在线观看 | 日本久久影视 | 国产123区| 久久久这里有精品999 | 福利视频一区二区思瑞 | 久久re热在线视频精99 | 男人猛进猛出女人下面视频 | 魔法满屋免费观看完整版中文 | 女仆色永久免费网站 | 天作谜案免费完整版在线观看 | 激情小说色图 | 国产精品性视频免费播放 | 国产一区二区免费不卡在线播放 | 亚洲国产综合久久久无码色伦 | 高清在线一区二区 | gay中国 | 久久热国产在线视频 | 青青青青在线视频 | 四虎永久在线精品波多野结衣 | 美女被扣逼 |