В этой статье представлены функции загрузки и загрузки Springboot.
1. Создать проект Springboot и добавить зависимости
Compile ("org.springframework.boot: Spring-Boot-Starter-Web") Compile ("org.springframework.boot: Spring-Boot-Starter-Thymeleaf")Справочник проекта:
Application.java Startup Class
Пакет Привет; Импорт org.springframework.boot.springapplication; Импорт org.springframework.boot.autoconfigure.springbootapplication; Импорт org.springframework.boot.context.properties.enableConfigurationProperties; @Springbootapplication public Class Application {public static void main (string [] args) {SpringApplication.run (Application.class, args); }}2. Создать тестовую страницу
Создайте новую uploadform.html в каталоге ресурсов/шаблонов
<html xmlns: th = "http://www.thymeleaf.org"> <body> <div th: if = "$ {message}"> <h2 th: text = "$ {сообщение}"/> </div> <div> <form method = "ectype =" multipart/form-data "action ="/"> <pire> <pire> <pire> <pire> <pire> <pire> <pire> <pire> <pire> <pire> <pire> <pire> <pire> <plode> <pire> <pire> <plode =" ectype = " upload: </td> <td> <input type = "file" name = "file"/> </td> </tr> <tr> <td> </td> <td> <input type = "value =" upload "/> </td> </tr> </table> </form> </div> <vil> <ul> <li: wangy =" file: $ a fily: Th: href = "$ {file}" rel = "enformlolow" th: text = "$ {file}"/> </li> </ul> </div> </body> </html>3. Создайте новую службу Storages Service
Storageservice интерфейс
Пакет Hello.storage; Импорт org.springframework.core.io.resource; Импорт org.springframework.web.multipart.multipartfile; Импорт java.nio.file.path; импортировать java.util.stream.stream; Общественный интерфейс Storageservice {void init (); void hore (multiousfile file); Stream <Thap> LoadAll (); PATH LOAD (String FileName); Ресурс LoadasResource (String FileName); void deleteAll (); }Реализация Storageservice
Пакет Hello.storage; Импорт org.springframework.core.io.resource; Импорт org.springframework.core.io.urlresource; Импорт org.springframework.stereotype.service; Импорт org.springframework.util.filesystemutils; Импорт org.springframework.util.stringutils; Импорт org.springframework.web.multipart.multipartfile; импортировать java.io.ioexception; Импорт java.net.malformedurlexception; Импорт java.nio.file.files; Импорт java.nio.file.path; Импорт java.nio.file.paths; импортировать java.nio.file.standardcopyoption; импортировать java.util.function.fedicate; импортировать java.util.stream.stream; @Service public class filesystemstorageservice реализует Storageservice {private final Path RootLocation = paths.get ("upload-dir"); / *** Сохранить файл** @param file file*/ @override public void store (multipartfile file) {string filename = stringutils.cleanpath (file.getoriginalfilename ()); try {if (file.isempty ()) {throw new StorageException («Не удалось сохранить пустой файл» + имя файла); } if (fileName.contains ("..")) {// Это проверка безопасности. Новое хранилище ("не может хранить файл с относительным путем за пределами текущего каталога" + filename); } Files.copy (file.getInputStream (), this.rootlocation.resolve (имя файла), standarcopyoption.replace_existing); } catch (ioException e) {бросить новое хранилище ("не удалось сохранить файл" + filename, e); }} /*** Перечислите все файлы ниже upload -dir* @return* /@override public Stream <Thpe> loadall () {try {return files.walk (this.Rootlocation, 1) // path ->! Path.equals (this.rootlocation) .filter (новый предикат <Thap> () {@OverRide public boolean test (pathocation pathoctocation root) }); } catch (ioException e) {бросить новое хранилище ("не удалось прочитать хранимые файлы", e); }} @Override public Path Load (String fileName) {return rootlocation.resolve (filename); } / *** Получить файловые ресурсы* @param filename Имя* @return resource* / @override public resource loadasresource (string fileName) {try {path file = load (filename); Ресурс ресурс = new urlresource (file.touri ()); if (resource.exists () || resource.isreadable ()) {return resource; } else {бросить новое storagefilenotfoundexception ("Не удалось прочитать файл:" + filename); }} catch (malformedurlexception e) {бросить новое хранилище filenotfoundexception ("Не удалось прочитать файл:" + filename, e); }} / *** Удалить все файлы в каталоге upload-dir* / @Override public void deleTeall () {fileSystemutils.deletetereCursive (rootlocation.tofile ()); } / **! } catch (ioException e) {бросить новое хранилище ("не может инициализировать хранение", e); }}}StorageException.java
Пакет Hello.storage; public Class StorageException Extends RuntimeException {public Storage Exception (String Message) {super (сообщение); } public StorageException (строковое сообщение, причина бросания) {super (сообщение, причина); }} StoragefilenotFoundException.javapackage hello.storage; открытый класс StoragefilenOtFoundException Extends StorageException {public StorageFilenOtFoundException (String Message) {super (сообщение); } public StorageFilenOtFoundException (строковое сообщение, причина бросания) {super (сообщение, причина); }}4. Создание контроллера
Поместите загруженные файлы в каталог upload-dir в проекте и по умолчанию перечислите загружаемые файлы на интерфейсе.
Функция ListUploadedFiles будет перечислять все файлы в текущем каталоге
File Download File File
Файл загрузки HandlefileUpload
Пакет Привет; импортировать java.io.ioexception; импортировать java.util.stream.collectors; Импорт org.springframework.beans.factory.annotation.autowired; Импорт org.springframework.core.io.resource; Импорт org.springframework.http.httphaders; Импорт org.springframework.http.responseentity; Import org.springframework.sterotype.controller; Импорт org.springframework.ui.model; Импорт org.springframework.web.bind.annotation.exceptionHandler; Импорт org.springframework.web.bind.annotation.getMaping; Импорт org.springframework.web.bind.annotation.pathvariable; Импорт org.springframework.web.bind.annotation.postmapping; Импорт org.springframework.web.bind.annotation.requestparam; Импорт org.springframework.web.bind.annotation.responsebody; Импорт org.springframework.web.multipart.multipartfile; Импорт org.springframework.web.servlet.mvc.method.annotation.mvcuricomponentsbuilder; Импорт org.springframework.web.servlet.mvc.support.redirectattributes; Импорт hello.storage.storagefilenotFoundException; Импорт hello.storage.storageservice; @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 -> mvcuricomomponentsbuilder.fromethodname (fileuploadcontroler.class, servfile ",", path.getFilename (). ToString ()). Build (). ToString ()) .collect (collectors.tolist ())); вернуть "uploadform"; } @GetMapping ("/files/{filename:.+}") @Responsebody public responseent <resource> servalfile (@pathvariable строкового файла) {resource file = storageservice.loadasresource (filename); return responseentity.ok (). Header (httphaders.content_disposition, "Attactment; filename =/" " + file.getFilename () +" /"").body(file); } @Postmapping ("/") public String harderupload (@RequestParam ("file") MultiplaWFile File, redirectattributes redirectattributes) {Storageservice.store (file); redirectattributes.addflashattribute («Сообщение», «Вы успешно загружены» + file.getoriginalfilename () + "!"); вернуть "перенаправление:/"; } @ExceptionHandler (StorageFilenOtFoundException.class) Public ReplyEntity <?> HandLestorageFilenOtFound (StoragefilenOtFoundException Exc) {return response.notFound (). Build (); }} Скачать исходный код: https://github.com/hellokittynii/springboot/tree/master/springbootuploadanddownload
Суммировать
Выше приведено исходный код для загрузки и загрузки файлов Springboot, представленных вам редактором. Я надеюсь, что это будет полезно для вас. Если у вас есть какие -либо вопросы, пожалуйста, оставьте мне сообщение, и редактор ответит вам вовремя. Большое спасибо за вашу поддержку сайту wulin.com!