十年網(wǎng)站開(kāi)發(fā)經(jīng)驗(yàn) + 多家企業(yè)客戶 + 靠譜的建站團(tuán)隊(duì)
量身定制 + 運(yùn)營(yíng)維護(hù)+專業(yè)推廣+無(wú)憂售后,網(wǎng)站問(wèn)題一站解決
本小節(jié)你將建立一個(gè)可以接受HTTP multi-part 文件的服務(wù)。
你將建立一個(gè)后臺(tái)服務(wù)來(lái)接收文件以及前臺(tái)頁(yè)面來(lái)上傳文件。
要利用servlet容器上傳文件,你要注冊(cè)一個(gè)MultipartConfigElement類(lèi),以往需要在web.xml 中配置
而在這里,你要感謝SpringBoot,一切都為你自動(dòng)配置好了。
1、新建一個(gè)文件上傳的Controller:
應(yīng)用已經(jīng)包含一些 存儲(chǔ)文件 和 從磁盤(pán)中加載文件 的類(lèi),他們?cè)赾n.tiny77.guide05這個(gè)包下。我們將會(huì)在FileUploadController中用到這些類(lèi)。
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 { Listpaths = 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 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(); } }