In diesem Artikel wird die Upload- und Download -Funktionen von Springboot vorgestellt.
1. Erstellen Sie das Springboot -Projekt und fügen Sie Abhängigkeiten hinzu
compile ("org.springframework.boot: Spring-Boot-Starter-Web") Compile ("org.springframework.boot: Spring-Boot-Starter-Thymeleaf")Das Projektverzeichnis lautet:
Application.java Startup -Klasse
Paket Hallo; import org.springframework.boot.springApplication; import org.springframework.boot.autoconfigure.springbootApplication; import org.springframework.boot.context.properties.enableConfigurationProperties; @SpringbootApplication öffentliche Klasse Anwendung {public static void main (String [] args) {SpringApplication.run (application.class, args); }}2. Erstellen Sie eine Testseite
Erstellen Sie im Verzeichnis Ressourcen/Vorlagen eine neue Uploadform.html
<html xmlns: th = "http://www.thymeleaf.org"> <body> <div th: if = "$ {message}"> <h2 th: text = "$ {message}"/> </div> <div> <form method = "post" cabled. Upload: </td> <td> <Eingabe type = "Datei" name = "Datei"/> </td> </tr> <tr> <td> </td> <td> <input type = "value =" upload "/> </td> </tr> </table> </Form> </div> <ul> <ul> <ul> <ul> <ul> <ul> <ul> <ul> <ul> <li -th: $ = $ · {{{div> <ul> <ul> <li th: $ = $ · {{ask. th: href = "$ {file}" rel = "externer nofollow" th: text = "$ {file}"/> </li> </ul> </div> </body> </html>3. Erstellen Sie einen neuen StorageService -Dienst
StorageService -Schnittstelle
Paket Hello.Storage; 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 -Datei); Stream <Path> loadAll (); Pfadlast (String -Dateiname); RessourcenlasteResource (String -Dateiname); void DeleteAll (); }StorageService -Implementierung
Paket Hello.Storage; 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; importieren java.io.ioException; importieren java.net.malformeDurlexception; importieren java.nio.file.files; Import Java.nio.file.Path; Import Java.nio.file.Paths; Import Java.nio.file.StandardCopyOption; import Java.util.Function.Predicate; import Java.util.stream.stream; @Service Public Class FilesSystemStorageService implementiert StorageService {private endgültige Pfad rootLocation = paths.get ("Upload-dir"); / *** Datei speichern** @param Datei Datei*/ @Override public void Store (MultiPartFile -Datei) {String Dateiname = Stringutils.cleanPath (Datei.GetOriginalFileName ()); try {if (Datei.isempty ()) {neue StorateException werfen ("Die leere Datei nicht speichern" + Dateiname); } if (Dateiname.contains ("..")) {// Dies ist eine Sicherheitsprüfung. } Files.copy (file.getInputStream (), this.rootLocation.resolve (Dateiname), StandardCopyOption.Replace_EXISTING); } catch (ioException e) {neue StorateException werfen ("fehlgeschlagene Datei" + Dateiname, e); }} /*** Listen Sie alle Dateien unten auf. }); } catch (ioException e) {neue StorateException werfen ("" gespeicherte Dateien nicht gelesen ", e); }} @Override public path load (String -Dateiname) {return rootLocation.resolve (Dateiname); } / *** Dateiressourcen abrufen* @param Dateiname Dateiname* @return Resource* / @Override public Resource loadAsResource (String -Dateiname) {try {Path -Datei = load (Dateiname); Ressourcenressource = new urlresource (file.touri ()); if (ressource.exists () || ressource.isreadable ()) {return ressource; } else {thrower New StorageFilenotFoundException ("konnte keine Datei lesen:" + Dateiname); }} catch (fehl Formaledurlexception E) {neue SpeicherfilenotfoundException ("konnte keine Datei lesen:" + Dateiname, e); }} / *** Alle Dateien im Upload-Dir-Verzeichnis löschen* / @Override public void deleteAll () {DateisystemeStemutils.deleteresiv (rootLocation.toFile ()); } / *** Initialisierung* / @Override public void init () {try {files.createdirectories (rootLocation); } catch (ioException e) {neue StorateException werfen ("konnte Speicher nicht initialisieren", e); }}}StorateException.java
Paket Hello.Storage; öffentliche Klasse StorateException erweitert RunTimeException {public StorageException (String -Nachricht) {Super (message); } public StorageException (String -Nachricht, Throwable Cause) {Super (Nachricht, Ursache); }} StorageFilenotFoundException.javapackage hello.storage; öffentliche Klasse StorageFilenotFoundException erweitert StorateException {public StorageFilenotFoundException (String -Nachricht) {Super (message); } public StorageFilenotFoundException (String -Nachricht, Throwable Cause) {Super (Nachricht, Ursache); }}4. Controller -Schöpfung
Fügen Sie die hochgeladenen Dateien in das Upload-Dir-Verzeichnis des Projekts ein und listen Sie standardmäßig die herunterladbaren Dateien auf der Schnittstelle auf.
ListUploadedFiles -Funktion listet alle Dateien im aktuellen Verzeichnis auf
Servile Download -Datei
Handladeladload -Datei
Paket Hallo; importieren java.io.ioException; 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.Reptity; 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; Hello.Storage.StorageFilenotFoundException importieren; Hello.Storage.StorageService importieren; @Controller public class FileUploadController {private final storageService storageService; @Autowired public FileUploadController (StorageService storageService) {this.storageService = storageService; } @GetMapping("/") public String listUploadedFiles(Model model) throws IOException { model.addAttribute("files", storageService.loadAll().map( path -> MvcUriComponentsBuilder.fromMethodName(FileUploadController.class, "serveFile", path.getFileName (). toString ()). build (). tostring ()) .collect (sammel.tolist ())); zurück "uploadform" zurückgeben; } @GetMapping ("/file/{Dateiname:.+}") @ResponseBody public responseTity <ressource> serveFile (@PathVariable String Dateiname) {Resource -Datei = StorageService.loadasResource (Dateiname); return responseEnentity.ok (). Header (httpheaders.content_disposition, "Attemment; Dateiname =/" " + file.getFileName () +" /").body(file); } @Postmapping ("/") public String handleFileUpload (@RequestParam ("Datei") MultiPartFile -Datei, recirectAttributes recirectTributes) {storageService.store (Datei); redirectAttributes.addflashAttribute ("message", "Sie erfolgreich hochgeladen" + file.getOriginalFileName () + "!"); return "recirect:/"; } @ExceptionHandler (StorageFilenotFoundException.class) public responseentity <?> HandlestorageFilenotfound (StorageFilenotFoundException exc) {return responseentity.notfound (). Build (); }} Quellcode -Download: https://github.com/hellokittynii/springboot/tree/master/springbootUploadandDownload
Zusammenfassen
Das obige ist der Quellcode zum Hochladen und Herunterladen von Springboot -Dateien, die Ihnen vom Editor vorgestellt wurden. Ich hoffe, es wird Ihnen hilfreich sein. Wenn Sie Fragen haben, hinterlassen Sie mir bitte eine Nachricht und der Editor wird Ihnen rechtzeitig antworten. Vielen Dank für Ihre Unterstützung auf der Wulin.com -Website!