国产片侵犯亲女视频播放_亚洲精品二区_在线免费国产视频_欧美精品一区二区三区在线_少妇久久久_在线观看av不卡

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

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

服務器之家 - 編程語言 - Java教程 - 基于Spring實現(xiàn)文件上傳功能

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

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

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

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

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

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

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

應用已經包含一些 存儲文件 和 從磁盤中加載文件 的類,他們在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可以基于它設定相應的路由。每一個@GetMapping和@PostMapping注解將綁定對應的請求參數(shù)和請求類型到特定的方法。

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

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

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

你需要提供一個服務接口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(
      "無權訪問該位置 "
        + 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、限制上傳文件的大小

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

4、應用啟動函數(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、運行結果

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

以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持服務器之家。

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

延伸 · 閱讀

精彩推薦
主站蜘蛛池模板: 亚洲人天堂| 午夜草民福利电影 | 国产一区二区视频在线观看 | 日本在线免费 | 亚洲入口| 女人久久久久久久 | 青青草国产精品 | 精品欧美一区二区三区久久久 | 国产一区在线视频观看 | 国产精品久久久久久亚洲调教 | 欧美精品一区二区三区在线 | 黄色网免费看 | 黄色成人av| 成人免费毛片高清视频 | 偷拍一区二区三区四区 | 黄色影片免费在线观看 | 欧美精品一区二区蜜臀亚洲 | 精品国产乱码久久久久久牛牛 | 久久久久久亚洲av毛片大全 | 在线激情视频 | 亚洲精品片 | 国产精品日韩一区二区 | 成人综合免费视频 | 亚洲成人av一区二区三区 | 欧美涩涩网站 | 国内自拍偷拍视频 | 国产91色 | 男人的天堂在线免费视频 | 久久五月视频 | 糈精国产xxxx在线观看 | 日韩久久久久久 | 国产精品久久久久久久浪潮网站 | 国产精品欧美大片 | 中文字幕 视频一区 | 日韩欧美中文字幕在线视频 | 中国黄色视屏 | 精品国产青草久久久久福利 | 中文字幕在线观看 | 欧美视频区 | 亚洲欧美日韩在线 | 日本a在线 |