Cet article présente les fonctions de téléchargement et de téléchargement de Springboot.
1. Créez un projet Springboot et ajoutez des dépendances
compiler ("org.springframework.boot: printemps-boot-starter-web") compile ("org.springframework.boot: printemp-boot-starter-thymeleaf")Le répertoire du projet est:
Classe de démarrage application.java
Package bonjour; 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); }}2. Créez une page de test
Créer un nouveau uploadform.html dans le répertoire Resources / Templates
<html xmlns: th = "http://www.thymeleaf.org"> <body> <div th: if = "$ {message}"> <h2 th: text = "$ {message}" /> </ div> <div> <form methethy = "post" Enctype = "multipart / form data" Action = "/"> <bout> upload: </td> <td> <input type = "file" name = "file" /> </td> </tr> <tr> <td> </td> <td> <input type = "soumi" value = "upload" /> </td> </tr> </ Table> </ Form> </div> <iv> <ul> <li th: every = "file: file {fichiers}"> <a th: href = "$ {file}" rel = "external nofollow" th: text = "$ {file}" /> </li> </ul> </div> </ body> </html>3. Créez un nouveau service de stockage de stockage
Interface de stockage
Package Hello.Storage; import org.springframework.core.io.resource; import org.springframework.web.multupar.MultiPartFile; import java.nio.file.path; import java.util.stream.stream; Interface publique StoringageService {void init (); VOID Store (fichier multipartfile); Stream <Athath> Loadall (); Path Load (String File Name); Resource LoadAsResource (String FileName); void Deleteall (); }Implémentation de stockage de stockage
Package Hello.Storage; import org.springframework.core.io.resource; import org.springframework.core.io.urlResource; import org.springframework.sterreotype.service; import org.springframework.util.filesystemutils; import org.springframework.util.stringutils; import org.springframework.web.multupar.MultiPartFile; Importer java.io.ioException; Importer java.net.malformedUrlexception; import java.nio.file.files; import java.nio.file.path; import java.nio.file.paths; Importer java.nio.file.standardCopyOption; import java.util.function.predicate; import java.util.stream.stream; @Service public class FileSystemStorageService implémente StorageService {private final path rootLocation = paths.get ("upload-dir"); / ** * Enregistrer le fichier * * @param fichier de fichier * / @Override public void Store (fichier multipartFile) {String filename = stringUtils.cleanPath (file.getoriginalFileName ()); essayez {if (file.isempty ()) {throw new StorageException ("Échec du fichier vide" + nom de fichier); } if (fileName.Contains ("..")) {// Ceci est un contrôle de sécurité New StorageException ("Impossible de stocker le fichier avec un chemin relatif en dehors du répertoire actuel" + FileName); } Files.copy (file.getInputStream (), this.rootlocation.resolve (filename), standardCopyOption.replace_existing); } catch (ioException e) {Throw New StorageException ("Échec du fichier" + nom de fichier, e); }} / ** * Répertoriez tous les fichiers ci-dessous Upload-Dir * @return * / @Override public Stream <Athath> Loadall () {try {return files.walk (this.rootlocation, 1) // path ->! Path.equals (this.rootlocation) .filter (new prédicat <atath> () {@Override boolean test (path) {return! }); } catch (ioException e) {lancez new StorageException ("Échec de la lecture de fichiers stockés", e); }} @Override Public Path Load (String FileName) {return rootLocation.Resolve (FileName); } / ** * Obtenez des ressources de fichiers * @param nom de fichier de fichier * @return Resource * / @Override Public Resource LoadAsResource (String FileName) {try {path File = Load (FileName); Ressource ressource = new UrlResource (file.touri ()); if (ressource.exists () || Resource.isReadable ()) {return Resource; } else {Throw New StorageFileNotFoundException ("n'a pas pu lire le fichier:" + nom de fichier); }} catch (MalformEdUrException e) {Throw New StorageFileNotFoundException ("Impossible de lire le fichier:" + FileName, E); }} / ** * Supprimer tous les fichiers dans le répertoire de téléchargement * / @Override public void Deleteall () {FileSystemUtils.deleterErandively (rootlocation.tofile ()); } / ** * Initialisation * / @Override public void init () {try {files.CreateDirectories (rootLocation); } catch (ioException e) {throw new StorageException ("n'a pas pu initialiser le stockage", e); }}}StorageException.java
Package Hello.Storage; public class StorageException étend RuntimeException {public StorageException (String Message) {super (message); } public StorageException (message de chaîne, cause thrognable) {super (message, cause); }} StorageFileNotFoundException.Javapackage Hello.Storage; public class StorageFileNotFoundException étend StorageException {public StorageFileNotFoundException (String Message) {super (message); } public StorageFileNotFoundException (message de chaîne, cause thrognable) {super (message, cause); }}4. Création du contrôleur
Mettez les fichiers téléchargés dans le répertoire Upload-DIR du projet et listez les fichiers téléchargeables sur l'interface par défaut.
La fonction ListTuploadFiles répertorie tous les fichiers dans le répertoire actuel
Fichier de téléchargement de service
Fichier de téléchargement HandleFileUpload
Package bonjour; Importer java.io.ioException; Importer 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.sterreotype.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.multupar.MultiPartFile; import org.springframework.web.servlet.mvc.method.annotation.mvcuriComponentsBuilder; import org.springframework.web.servlet.mvc.support.redirectattributes; Importer hello.storage.storageFileNotFoundException; Importer hello.storage.storageService; @Controller public class FileuploadController {private final storageService StorageService; @Autowired Public FileUploadController (StorageService StorageService) {this.storageService = StorageService; } @Getmapping ("/") public String listUploadFiles (modèle modèle) lève ioException {Model.AddAttribute ("Files", storageService.Loadall (). Map (Path -> mvcuRICOPONENTSBUILDER.FROMITHODNAME (FileuploadController.Class, "ServeFile", path.getFileName (). toString ()). build (). toString ()) .Collect (collectionners.tolist ())); return "uploadform"; } @GetMapping ("/ Files / {FileName:. +}") @ResponseBody Public ResponseNtity <Source> ServeFile (@Pathvariable String fileName) {Resource File = StorageService.LoadasResource (FileName); return Responsentity.ok (). En-tête (httpheaders.content_disposition, "pièce jointe; filename = /" "+ file.getFileName () +" /"").body(file); } @Postmapping ("/") Public String HandleFilePload (@RequestParam ("Fichier") Fichier multipartFile, RedirectAttributes RedirectAttributes) {StorageService.Store (fichier); redirectattributes.addflashattribute ("message", "vous avez téléchargé avec succès" + file.getoriginalFileName () + "!"); retourner "rediriger: /"; } @ExceptionHandler (StorageFileNotFoundException.class) Public Responsentity <?> HandleStorageFileNotFound (StorageFilenotFoundException Exc) {return réponsentity.notFound (). Build (); }} Téléchargement du code source: https://github.com/hellokittynii/springboot/tree/master/springbootuploadanddownload
Résumer
Ce qui précède est le code source pour le téléchargement et le téléchargement de fichiers Springboot qui vous sont présentés par l'éditeur. J'espère que cela vous sera utile. Si vous avez des questions, veuillez me laisser un message et l'éditeur vous répondra à temps. Merci beaucoup pour votre soutien au site Web Wulin.com!