Este artículo presenta las funciones de carga y descarga de SpringBoot.
1. Cree el proyecto SpringBoot y agregue dependencias
compile ("org.springframework.boot: spring-boot-starter-web") compile ("org.springframework.boot: spring-boot-starter-thymeleaf")El directorio del proyecto es:
Clase.java startups
paquete hola; 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. Cree una página de prueba
Cree un nuevo uploadform.html en el directorio de recursos/plantillas
<html xmlns: th = "http://www.thymeleaf.org"> <body> <div th: if = "$ {message}"> <h2 th: text = "$ {Message}"/> <//port> <div> <div método = "post" enctype = "multipart/formal-data" Action = "/"> <tave> <tr> subiendo: </td> <td> <input type = "file" name = "file"/> </td> </tr> <tr> <tr> <td> </td> <td> <input type = "enviar" valor = "cargar"/> </td> </tr> </box> </form> </div> <div> <li> <li th: cada = "file: $ {file> th: href = "$ {file}" rel = "externo nofollow" th: text = "$ {file}"/> </li> </ul> </div> </body> </html>3. Cree un nuevo servicio de servicio de almacenamiento
Interfaz de servicio almacenado
Paquete Hello.Storage; importar org.springframework.core.io.resource; importar org.springframework.web.multipart.multipartfile; import java.nio.file.path; import java.util.stream.stream; Interfaz pública StorageService {void init (); tienda void (archivo multipartfile); Stream <Path> LoadAll (); Carga de ruta (nombre de archivo de cadena); Recursos LoadAsResource (nombre de archivo de cadena); void deleteall (); }Implementación de servicio almacenamiento
Paquete Hello.Storage; importar org.springframework.core.io.resource; importar org.springframework.core.io.urlresource; importar org.springframework.stereotype.service; importar org.springframework.util.filesystemUtils; importar org.springframework.util.stringutils; importar org.springframework.web.multipart.multipartfile; import java.io.ioException; import java.net.malFormedUrexception; import java.nio.file.files; import java.nio.file.path; import java.nio.file.path; import java.nio.file.StandardCopyOption; import java.util.function.predicate; import java.util.stream.stream; @Service public class Files SystemStorageService implementa StoragesService {PRIVADA final RootLocation = Paths.get ("upload-Dir"); / *** Guardar archivo** @param archivo de archivo*/ @override public void store (archivo multipartfile) {string filename = stringUtils.cleanPath (file.getOriginalFileName ()); intente {if (file.isEmpty ()) {tire nueva almacenamientoException ("no se pudo almacenar el archivo vacío" + nombre de archivo); } if (FileName.Contains ("..")) {// Esta es una verificación de seguridad, arroje nuevo almacenamiento, "no puede almacenar el archivo con ruta relativa fuera del directorio actual" + nombre de archivo); } Files.Copy (file.getInputStream (), this.rootlocation.resolve (nombre de archivo), StandardCopyOption.replace_Existing); } catch (ioException e) {tire nueva almacenamientoException ("no pudo almacenar archivo" + nombre de archivo, e); }} /*** Enumere todos los archivos a continuación cargue -dir* @return* /@Override public stream <Path> loadAll () {try {return files.walk (this.rootlocation, 1) // rath ->! }); } Catch (ioException e) {Throw New StorageException ("Error al leer archivos almacenados", e); }} @Override public Path Load (String FileName) {return rootLocation.resolve (nombre de archivo); } / *** Obtenga recursos de archivo* @param Nombre del archivo del nombre de archivo* @return recource* / @Override público recursos LoadAsResource (string filename) {try {Path file = load (fileName); Recursos recursos = new UrlResource (file.touri ()); if (resource.exists () || resource.iseadable ()) {return Resource; } else {lanzar nueva almacenamientofilenotfoundException ("no se pudo leer el archivo:" + nombre de archivo); }} Catch (MalFormedUrLeCeption e) {lanzar nueva almacenamientofilenotfoundException ("no se pudo leer el archivo:" + nombre de archivo, e); }} / *** Elimine todos los archivos en el directorio de carga-DIR* / @Override public void DeleteAll () {filesSystemUtils.deleterCursive (rootLocation.tofile ()); } / *** Inicialización* / @Override public void init () {try {files.createDirectorios (rootLocation); } Catch (ioException e) {Throw New StorageException ("no se pudo inicializar el almacenamiento", e); }}}StorageException.java
Paquete Hello.Storage; public class StorageException extiende RuntimeException {public StorageException (string Message) {super (mensaje); } public StorageException (mensaje de cadena, causa de lanzamiento) {super (mensaje, causa); }} StorageFilenotFoundException.javapAckage Hello.Storage; public class StorageFilenotFoundException extiende StorageException {public StorageFilenotFoundException (string Message) {super (mensaje); } public StorageFilenotFoundException (mensaje de cadena, causa de lanzamiento) {super (mensaje, causa); }}4. Creación del controlador
Coloque los archivos cargados en el directorio de carga-DIR del proyecto y enumere los archivos descargables en la interfaz de forma predeterminada.
La función ListuploadedFiles enumerará todos los archivos en el directorio actual
archivo de descarga de servicio de servicio
archivo de carga de manegultoad
paquete hola; import java.io.ioException; import 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.stereotype.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; import hello.storage.storageFilenotFoundException; importar hello.storage.storageservice; @Controller public class FileUploadController {storageService storageService final privado; @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 (Collectors.Tolist ())); return "cargar forma"; } @Getmapping ("/files/{nombre de archivo :.+}") @ResponseBody Public ResponseEntity <conseurce> ServFile (@PathVariable String FileName) {recource archivo = storageservice.loadAsResource (fileName); return responseEntity.ok (). Header (httpheaders.content_disposition, "adjunto; filename =/" " + file.getFileName () +" /"").body(file); } @PostMapping ("/") Cadena pública HandleFileUpload (@RequestParam ("File") File multipartfile, redirectAttributes redirectatTributes) {storageservice.store (archivo); redirectattributes.AddFlashAttribute ("Mensaje", "Usted cargó con éxito" + file.getOriginalFileName () + "!"); return "redirect:/"; } @ExceptionHandler (StorageFileNotFoundException.Class) Public ResponseEntity <?> HandLeStorageFilenotFound (StorageFilenotFoundException exc) {return ResponseEntity.NotFound (). Build (); }} Descarga del código fuente: https://github.com/hellokittynii/springboot/tree/master/springbootuploadanddownload
Resumir
El anterior es el código fuente para cargar y descargar archivos SpringBoot presentados por el editor. Espero que te sea útil. Si tiene alguna pregunta, déjame un mensaje y el editor le responderá a tiempo. ¡Muchas gracias por su apoyo al sitio web de Wulin.com!