Автор оригинала: Nilmadhab mondal.
Начните писать Мы разработаем сервис загрузки файлов, который будет использоваться для загрузки изображений в наше приложение для электронной коммерции с помощью Java Spring Boot
Нам нужна была функция загрузки изображений для нашего приложения электронной коммерции, так как нам нужно загружать изображения для продуктов и категорий. Мы создадим эту функцию как отдельную услугу, которую можно будет использовать позже. Вы можете использовать этот исходный код для загрузки и отображения изображений для любого из ваших продуктов.
Сначала мы создадим серверную часть на Java и Spring, а затем интегрируем ее с веб-клиентом и клиентом Android в других учебных пособиях
Вы можете протестировать демонстрационную загрузку файла здесь
Найдите полный код здесь
У нас будет 3 API 1. Загрузите изображение 2. Получите изображение по его названию 3. Получить все изображения
Давайте взглянем на FileUploadController
Класс Java, который описывает выше 3 API
package com.webtutsplus.ecommerce.controller; import com.webtutsplus.ecommerce.model.FileInfo; import com.webtutsplus.ecommerce.service.FIleStoreService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.core.io.Resource; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.*; import org.springframework.web.multipart.MultipartFile; import org.springframework.web.servlet.mvc.method.annotation.MvcUriComponentsBuilder; import java.io.IOException; import java.nio.file.Path; import java.util.List; import java.util.stream.Collectors; import java.util.stream.Stream; @RestController @RequestMapping("/fileUpload") public class FileUploadController { @Autowired FIleStoreService fileStoreService; //upload a file @PostMapping("/") public String handleFileUpload(@RequestParam("file") MultipartFile file) { return fileStoreService.store(file); } // get all the files @GetMapping("/") public ResponseEntity> getListFiles() { // first get a stream of all file path present in root file directory Stream
pathStream = fileStoreService.loadAll(); List fileInfos = pathStream.map(path -> { // get file name String filename = path.getFileName().toString(); // use function to get one file to build the URL String url = MvcUriComponentsBuilder .fromMethodName(FileUploadController.class, "getFile", path.getFileName().toString()).build().toString(); // make a fileinfo object from filename and url return new FileInfo(filename, url); }).collect(Collectors.toList()); return ResponseEntity.status(HttpStatus.OK).body(fileInfos); } // get file by filename @GetMapping("/files/{filename:.+}") public ResponseEntity getFile(@PathVariable String filename) { Resource file = fileStoreService.load(filename); return ResponseEntity.ok() .header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + file.getFilename() + "\"").body(file); } }
который вызывает Служба хранилища файлов
, которая также содержит 3 метода для каждого API соответственно. Я добавил множество комментариев к коду. Пожалуйста, прокомментируйте ниже, если что-то не ясно.
package com.webtutsplus.ecommerce.service; import com.webtutsplus.ecommerce.constants.Constants; import com.webtutsplus.ecommerce.exceptions.StorageException; import org.apache.commons.io.FilenameUtils; import org.springframework.core.io.Resource; import org.springframework.core.io.UrlResource; import org.springframework.stereotype.Service; import org.springframework.web.multipart.MultipartFile; import org.springframework.web.servlet.support.ServletUriComponentsBuilder; import java.io.IOException; import java.io.InputStream; import java.net.MalformedURLException; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.nio.file.StandardCopyOption; import java.util.UUID; import java.util.stream.Stream; @Service public class FIleStoreService { Path rootLocation = Paths.get(Constants.UPLOAD_FILE_DIR); public String store(MultipartFile file) { try { if (file.isEmpty()) { throw new StorageException("Failed to store empty file."); } // find extension of the file,png or jpg String extension = FilenameUtils.getExtension(file.getOriginalFilename()); // generate a random unique name for the image String uploadedFileName = UUID.randomUUID().toString() + "." + extension; // create a path for destination file Path destinationFile = rootLocation.resolve(Paths.get(uploadedFileName)) .normalize().toAbsolutePath(); // Copy input file to destination file path try (InputStream inputStream = file.getInputStream()) { Files.copy(inputStream, destinationFile, StandardCopyOption.REPLACE_EXISTING); final String baseUrl = ServletUriComponentsBuilder.fromCurrentContextPath().build().toUriString(); //create the public Image URl where we can find the image final StringBuilder imageStringBuilder = new StringBuilder(baseUrl); imageStringBuilder.append("/fileUpload/files/"); imageStringBuilder.append(uploadedFileName); return imageStringBuilder.toString(); } } catch (IOException e) { throw new StorageException("Failed to store file.", e); } } public StreamloadAll() { // load all the files try { return Files.walk(this.rootLocation, 1) // ignore the root path .filter(path -> !path.equals(this.rootLocation)) .map(this.rootLocation::relativize); } catch (IOException e) { throw new StorageException("Failed to read stored files", e); } } public Resource load(String filename) { try { // read the file based on the filename Path file = rootLocation.resolve(filename); // get resource from path Resource resource = new UrlResource(file.toUri()); if (resource.exists() || resource.isReadable()) { return resource; } else { throw new RuntimeException("Could not read the file!"); } } catch (MalformedURLException e) { throw new RuntimeException("Error: " + e.getMessage()); } } }
Вот и все, теперь файлы будут переименованы с уникальным именем, сохраненным в **_UPLOAD_FILE_DIR_**
каталог* * . **
[
Загрузить файл
получите все загруженные файлы
Мы создадим приложение для Android , которое будет использовать API. Конечный результат будет выглядеть примерно так.
здесь…
Оригинал: “https://www.codementor.io/@nilmadhab/let-s-develop-file-upload-service-from-scratch-using-java-and-spring-boot-1e4tvdcja4”