Este artigo apresenta as funções de upload e download do Springboot.
1. Crie projeto de trampolim e adicione dependências
Compile ("org.springframework.boot: spring-boot-starter-web") Compile ("org.springframework.boot: primavera-boot-starter-tymymeleaf")O diretório do projeto é:
Application.java Startup Class
pacote olá; importar org.springframework.boot.springApplication; importar org.springframework.boot.autoconfigure.springbootApplication; importar org.springframework.boot.context.properties.enableConfigurationProperties; @SpringbooTApplication public class Application {public static void main (string [] args) {springapplication.run (Application.class, args); }}2. Crie uma página de teste
Crie um novo uploadForm.html no diretório Recursos/Modelos
<html xmlns: th = "http://www.thymeleaf.org"> <body> <div th: if = "$ {message}"> <h2 th: text = "$ {message}"/> </div> <div> <form = "pós" "Enctype =") upload: </td> <td> <input type = "file" name = "file"/> </td> </tr> <tr> <td> </td> <td> <input type = "submit" value = "upload"/> </td> </tr> </table> </forma "</div> th: href = "$ {file}" rel = "Nofollow externo" th: text = "$ {file}"/> </li> </ul> </div> </body> </html>3. Crie um novo serviço de armazenamento
Interface de estorages Service
pacote hello.storage; importar org.springframework.core.io.resource; importar org.springframework.web.multipart.multipartFile; importar java.nio.file.path; importar java.util.stream.stream; interface pública StorageService {void init (); Void Store (arquivo multipart -arquivo); Stream <TACH> loadAll (); Carga de caminho (nome do arquivo de string); Recurso loadAsResource (nome do arquivo de string); void DeLeTeall (); }Implementação de StorageService
pacote hello.storage; importar org.springframework.core.io.resource; importar org.springframework.core.io.urlResource; importar org.springframework.tereotype.service; importar org.springframework.util.filesystemutils; importar org.springframework.util.stringutils; importar org.springframework.web.multipart.multipartFile; importar java.io.ioException; importar java.net.MalformEdUrlexception; importar java.nio.file.files; importar java.nio.file.path; importar java.nio.file.paths; importar java.nio.file.standardcopyOption; importar java.util.function.predicate; importar java.util.stream.stream; @Service Public Class FileSystemStorageService implementa StorageService {private Final Path RootLocation = Paths.get ("Upload-Dir"); / *** Salvar arquivo** arquivo de arquivo @param*/ @Override public void Store (arquivo multipartFile) {string filename = stringUtils.cleanPath (file.getoriginalfileName ()); tente {if (file.isEmpty ()) {lança a nova armazenamento ("Falha ao armazenar o arquivo vazio" + nome do arquivo); } if (filename.contains ("..")) {// Este é um cheque de segurança lançar uma nova armazenamento ("Não é possível armazenar arquivo com caminho relativo fora do diretório atual" + nome do arquivo); } Files.copy (file.getInputStream (), this.rootLocation.resolve (nome do arquivo), StandardCopyOption.replace_existing); } catch (ioexception e) {lança nova storageException ("Falha ao armazenar o arquivo" + nome do arquivo, e); }} /*** Liste todos os arquivos abaixo do upload -Dir* @return* /@Override public Stream <Path> loadall () {try {return files.walk (this.rootLocation, 1) // path ->! Path.Equals (thisrootLocation) .fter (novo predicado <ty> () {@override Pathath Path Pathathanan). }); } catch (ioexception e) {lança nova storageException ("Falha ao ler arquivos armazenados", e); }} @Override Public Path Load (String filename) {return rootLocation.Resolve (nome do arquivo); } / *** Obtenha recursos do arquivo* @param fileName Name Nome* @return Resource* / @Override Public Resource loadAsResource (string filename) {try {path file = load (fileName); Recurso de recurso = novo urlResource (file.touri ()); if (Resource.Exists () || Resource.isReadable ()) {return Resource; } else {lança new storageFilENotFoundException ("não conseguiu ler o arquivo:" + nome do arquivo); }} catch (malformEdUrlexception e) {lança o novo armazenamentoFilENOTFoundException ("não conseguiu ler o arquivo:" + nome do arquivo, e); }} / *** Exclua todos os arquivos no diretório upload-Dir* / @Override public void DeLeTeall () {filesystemutils.deletereCursive (rootLocation.tofile ()); } / *** Inicialização* / @Override public void init () {try {files.createDirectories (rootlocation); } catch (ioexception e) {lança a nova armazenamento ("não foi possível inicializar o armazenamento", e); }}}StorageException.java
pacote hello.storage; public class StorageException estende RUNTimeException {public storageException (string message) {super (mensagem); } public storageException (mensagem de string, causa de arremesso) {super (mensagem, causa); }} StorageFilENotFoundException.javapackage hello.storage; public class StorageFilENotFoundException estende o armazenamento {public storageFilENotFoundException (string message) {super (mensagem); } public storageFilENOTFoundException (mensagem de string, causa de arremesso) {super (mensagem, causa); }}4. Criação do controlador
Coloque os arquivos enviados no diretório Upload-Dir do projeto e liste os arquivos para download na interface por padrão.
A função listuploadedfiles listará todos os arquivos no diretório atual
Arquivo de download de servir
HandleFileUpload Upload File
pacote olá; importar java.io.ioException; importar java.util.stream.collectores; importar org.springframework.beans.factory.annotation.autowired; importar org.springframework.core.io.resource; importar org.springframework.http.httpheaders; importar org.springframework.http.Responseentity; importar org.springframework.tereotype.controller; importar org.springframework.ui.model; importar org.springframework.web.bind.annotation.exceptionHandler; importar org.springframework.web.bind.annotation.getMapping; importar org.springframework.web.bind.annotation.pathvariable; importar org.springframework.web.bind.annotation.postMapping; importar org.springframework.web.bind.annotation.requestparam; importar org.springframework.web.bind.annotation.ResponseBody; importar org.springframework.web.multipart.multipartFile; importar org.springframework.web.servlet.mvc.method.annotation.mvcuricomponentsbuilder; importar org.springframework.web.servlet.mvc.support.redirectattributes; importação hello.storage.StorageFilENotFoundException; importação hello.storage.storageService; @Controller public class FileUploadController {private final StorageService StorageService; @AUTowired public fileUploadController (StorageService StorageService) {this.storageservice = storageService; } @GetMapping ("/") public string listuploadedfiles (modelo modelo) lança ioexception {model.addattribute ("arquivos", storageService.loadall (). Map (path -> mvcuricomentsbuilder.frommethodName (fileUploadControlller.class.class, "servir", " path.getfilename (). tostring ()). build (). tostring ()) .collect (collectors.tolist ())); return "uploadform"; } @GetMapping ("/files/{filename:.+}") @ResponseBody Public ResponseEntity <Source> servfile (@PathVariable string filename) {arquivo de recursos = storageService.loadAsResource (nome do arquivo); RETORNO DE REPORTIÇÃOENTITY.OK (). Cabeçalho (httpheaders.content_dispition, "Anexamento; nome do arquivo =/" " + file.getFileName () +" /"").Bodybody(File); } @PostMapping ("/") public String handleFileUpload (@RequestParam ("FILE") arquivo multipart de arquivo, redirectattributes redirectattributes) {storageService.store (arquivo); redirectattributes.addflashattribute ("mensagem", "você carregou com sucesso" + file.getoriginalfileName () + "!"); retornar "redirecionar:/"; } @ExceptionHandler (StorageFilENotFoundException.Class) Resposta pública <?> HandleStorageFilENotFound (StorageFileNotFoundException exc) {Return ResponseEntity.NotFound (). Build (); }} Download do código -fonte: https://github.com/hellokittynii/springboot/tree/master/springbootuploadanddownload
Resumir
O exposto acima é o código -fonte para fazer upload e baixar arquivos de troca de troca introduzidos pelo editor. Espero que seja útil para você. Se você tiver alguma dúvida, deixe -me uma mensagem e o editor responderá a você a tempo. Muito obrigado pelo seu apoio ao site wulin.com!