>  기사  >  Java  >  Spring Boot를 통해 파일 및 스토리지 서비스를 구현하는 방법

Spring Boot를 통해 파일 및 스토리지 서비스를 구현하는 방법

PHPz
PHPz원래의
2023-06-22 12:26:30913검색

인터넷 기술의 발전으로 파일 및 스토리지 서비스는 다양한 애플리케이션의 필수 구성 요소가 되었습니다. Spring Boot는 엔터프라이즈 수준의 Java 애플리케이션을 빠르게 구축하기 위한 프레임워크로서 파일 및 스토리지 서비스를 구현하는 데에도 고유한 이점을 가지고 있습니다. 이번 글에서는 Spring Boot를 통해 파일과 스토리지 서비스를 구현하는 방법을 소개하겠습니다.

1. Spring Boot의 파일 처리

Spring Boot는 Spring의 Resource 및 ResourceLoader 인터페이스를 통해 로컬 파일, 클래스 경로에 있는 파일, 네트워크 리소스 등을 얻을 수 있습니다.

1.1 로컬 파일 작업

Spring Boot 개발 프로세스에서는 지정된 파일의 Resource 객체를 가져오기 위해 ResourceLoader 인터페이스의 getResource 메서드를 사용합니다.

@ResourceLoader
ResourceLoader resourceLoader;

File file = new File("D:/image.jpg"); //指定文件路径(绝对路径)
Resource resource = resourceLoader.getResource("file:" + file.getAbsolutePath()); //获取文件Resource对象
InputStream inputStream = resource.getInputStream(); //获取文件输入流

그 중 ResourceLoader는 다음과 같습니다. Spring에서 제공하는 리소스 로더 인터페이스 Autowired를 통해 구현 클래스의 인스턴스를 자동으로 주입하도록 @ResourceLoader 주석을 표시할 수 있습니다. getResource() 메소드는 지정된 파일 경로의 Resource 객체를 얻는 데 사용됩니다. 여기서는 "file:" 프로토콜을 통해 절대 경로를 지정합니다.

1.2 클래스 경로 파일 작업

Spring Boot 애플리케이션에서는 클래스 경로 아래에 웹 프로젝트와 관련된 리소스 파일(예: 구성 파일)을 넣고 ClassPathResource를 통해 리소스 참조를 얻을 수 있습니다.

ClassPathResource classPathResource = new ClassPathResource("config.properties"); //获取配置文件Resource对象
InputStream inputStream = classPathResource.getInputStream(); //获取配置文件输入流

ClassPathResource 클래스가 로드 중입니다. 애플리케이션 클래스 경로의 리소스는 "classpath:" 및 "file:"과 같은 파일 시스템 접두사로 지원됩니다. 이 코드는 기본 경로 접두사 "file:"을 기준으로 파일 시스템 접두사를 사용하는 방법을 보여줍니다. 지정되지 않았습니다.

1.3 네트워크 파일 작업

Spring Boot는 로컬 및 클래스 경로에 있는 파일 외에도 URLResource 개체를 통해 네트워크에 있는 파일을 작업할 수도 있습니다. 코드 예제는 다음과 같습니다.

String url = "http://img.iplaysoft.com/wp-content/uploads/2019/free-images/free_stock_photo.jpg";
Resource resource = new UrlResource(url); //获取网络资源Resource对象
InputStream inputStream = resource.getInputStream(); //获取网络资源输入流

그 중 UrlResource 클래스는 리소스를 얻을 수 있습니다. 네트워크 파일에서 네트워크 주소 URL을 생성자의 매개변수로 전달해야 합니다.

2. Spring Boot의 파일 업로드

실제 Spring Boot 애플리케이션 개발에서는 파일 업로드가 일반적인 요구 사항입니다. Spring Boot에서는 MultipartFile 클래스와 MultipartResolver 파서를 사용하여 파일 업로드 작업을 완료할 수 있습니다.

2.1 MultipartFile 클래스

Spring의 MultipartFile 클래스는 하나 이상의 파일을 업로드하는 간단하고 일관된 방법을 제공합니다. @RequestParam 주석 아래에 사용되는 MVC 처리 방법의 매개변수 유형입니다. 예:

@PostMapping("/upload")
@ResponseBody
public String upload(@RequestParam("file") MultipartFile file) {
    //具体文件上传操作
    return "success";
}

파일을 업로드할 때 특정 업로드 작업을 지정하고 파일 저장 경로와 같은 관련 매개변수를 설정해야 합니다.

@PostMapping("/upload")
@ResponseBody
public String upload(@RequestParam("file") MultipartFile file) {
    // 获取文件名
    String fileName = file.getOriginalFilename();
    // 设置保存路径
    String filePath = "D:/upload/";
    File dest = new File(filePath + fileName);
    try {
        file.transferTo(dest);
        // 具体业务操作
        return "success";
    } catch (IOException e) {
        e.printStackTrace();
        return "failure";
    }
}

2.2 MultipartResolver Resolver

MultipartResolver는 POST 요청에서 파일 업로드 데이터를 구문 분석하는 데 사용되는 Spring MVC 프레임워크의 인터페이스입니다. Spring Boot에서는 내장된 CommonsMultipartResolver 클래스를 사용하여 파일 업로드 구문 분석 작업을 구현할 수 있습니다. Spring Boot 프로젝트에서는 Spring 구성 파일에 MultipartResolver 개체만 구성하면 됩니다. 구체적인 코드 예제는 다음과 같습니다.

@Configuration
@EnableWebMvc
public class WebConfig implements WebMvcConfigurer {

    @Bean
    public MultipartResolver multipartResolver() {
        CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver();
        multipartResolver.setMaxUploadSize(1000000);
        return multipartResolver;
    }
}

이 예제에서는 CommonsMultipartResolver 클래스 인스턴스를 구성하고 업로드되는 파일의 최대 크기를 1,000,000바이트로 제한합니다. . Spring MVC 적응형 동작을 활성화하려면 @EnableWebMvc를 활성화해야 CommonsMultipartResolver 클래스 인스턴스가 올바르게 작동할 수 있습니다.

3. Spring Boot에서 파일 다운로드

Spring Boot 애플리케이션 개발에서는 파일 다운로드도 일반적인 요구 사항입니다. Spring Boot는 해당 상태 코드, 헤더 및 본문을 포함하는 전체 HTTP 응답을 나타내는 ResponseEntity를 제공합니다. Content-Disposition을 설정하여 다운로드 파일 이름과 유형을 지정할 수 있습니다.

3.1 파일 다운로드 구현

@ResponseBody 주석을 사용하여 메서드에서 반환된 바이트 배열로 표시되는 파일 콘텐츠를 처리한 다음 ResponseEntity를 사용하여 전체 HTTP 응답 본문을 반환할 수 있습니다.

@GetMapping("/download")
public ResponseEntity<byte[]> download() throws IOException {
    String filePath = "D:/image.jpg";
    File file = new File(filePath);
    HttpHeaders headers = new HttpHeaders();
    headers.add("Content-Disposition", "attachment;filename=" + file.getName());
    headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
    byte[] bytes = FileUtils.readFileToByteArray(file);
    ResponseEntity<byte[]> responseEntity = new ResponseEntity<>(bytes, headers, HttpStatus.OK);
    return responseEntity;
}

위 코드에서는 FileUtils를 사용하여 파일을 바이트 배열로 읽고 배열을 HttpEntity로 설정한 후 반환합니다. 반환된 HttpEntity에서는 클라이언트 브라우저가 다운로드 창에 이 정보를 표시할 수 있도록 파일의 이름과 유형도 지정합니다.

3.2 다중 파일 다운로드 달성

경우에 따라 여러 파일을 다운로드해야 하며 여러 파일을 zip 파일로 패키지하여 다중 파일 다운로드를 수행할 수 있습니다. Spring Boot는 java.util.zip 패키지에서 제공하는 ZipOutputStream 클래스를 사용하여 zip 파일 작업을 쉽게 구현합니다.

@GetMapping("/download_multi")
public ResponseEntity<byte[]> downloadMulti() throws IOException {
    String base = "D:/test/";
    File directoryToZip = new File(base);
    List<File> fileList = new ArrayList<>();
    getAllFiles(directoryToZip, fileList);
    byte[] zipBytes = getZipBytes(fileList, base);
    HttpHeaders headers = new HttpHeaders();
    headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
    headers.add("Content-Disposition", "attachment; filename="files.zip"");
    headers.setContentLength(zipBytes.length);
    ResponseEntity<byte[]> responseEntity = new ResponseEntity<>(zipBytes, headers, HttpStatus.OK);
    return responseEntity;
}

private byte[] getZipBytes(List<File> fileList, String basePath) throws IOException {
    ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
    ZipOutputStream zipOutputStream = new ZipOutputStream(outputStream);
    for (File file : fileList) {
        String filePath = file.getAbsolutePath().substring(basePath.length());
        ZipEntry zipEntry = new ZipEntry(filePath);
        zipOutputStream.putNextEntry(zipEntry);
        FileInputStream inputStream = new FileInputStream(file);
        IOUtils.copy(inputStream, zipOutputStream);
        inputStream.close();
        zipOutputStream.closeEntry();
    }
    zipOutputStream.close();
    byte[] bytes = outputStream.toByteArray();
    outputStream.close();
    return bytes;
}

private void getAllFiles(File dir, List<File> fileList) {
    File[] files = dir.listFiles();
    for (File file : files) {
        if (file.isDirectory()) {
            getAllFiles(file, fileList);
        } else {
            fileList.add(file);
        }
    }
}

위 코드에서는 ZipOutputStream 클래스와 ByteArrayOutputStream을 사용하여 여러 파일을 하나의 파일로 패키징합니다. zip 파일, 클라이언트 브라우저가 다운로드 창에 이 정보를 표시할 수 있도록 zip 파일의 바이트 배열, 파일 이름 및 유형을 포함하여 ResponseEntity를 통해 전체 HTTP 응답 본문을 반환합니다.

4. Spring Boot의 파일 저장

실제 애플리케이션에서는 파일 저장도 중요한 링크입니다. 로컬, FTP, 객체 스토리지 등 다양한 위치에 파일을 저장할 수 있는데 여기서는 로컬 스토리지를 예로 들어 Spring Boot를 통해 파일 스토리지를 구현하는 방법을 소개하겠습니다.

4.1 저장소 디렉터리 만들기

먼저 저장소 서비스를 위한 디렉터리를 만들어야 합니다. 코드 예시는 다음과 같습니다.

String fileRoot = "/data/files/";
Path rootPath = Paths.get(fileRoot).normalize().toAbsolutePath();
if (!Files.exists(rootPath)) {
    Files.createDirectories(rootPath);
}

위 코드에서는 파일을 저장할 루트 디렉터리 /data/files/를 만듭니다. 디렉토리가 존재하는지 확인하십시오. 존재하지 않으면 작성하십시오.

4.2 实现文件存储服务

在Spring Boot中,实现文件存储服务也非常简单,我们可以创建一个类实现存储服务接口,具体代码示例如下:

@Service
public class FileStorageService {

    private Path fileStorageLocation;

    @Autowired
    public FileStorageService(@Value("${file.upload-dir}") String fileRoot) {
        this.fileStorageLocation = Paths.get(fileRoot).normalize().toAbsolutePath();
        try {
            Files.createDirectories(this.fileStorageLocation);
        } catch (Exception e) {
            throw new FileStorageException("Could not create the directory where the uploaded files will be stored.", e);
        }
    }

    public String storeFile(MultipartFile file) {
        String fileName = StringUtils.cleanPath(file.getOriginalFilename());
        try {
            if (fileName.contains("..")) {
                throw new FileStorageException("Sorry! Filename contains invalid path sequence " + fileName);
            }
            Path targetLocation = this.fileStorageLocation.resolve(fileName);
            Files.copy(file.getInputStream(), targetLocation, StandardCopyOption.REPLACE_EXISTING);
            return fileName;
        } catch (IOException ex) {
            throw new FileStorageException("Could not store file " + fileName + ". Please try again!", ex);
        }
    }

    public Resource loadFileAsResource(String fileName) {
        try {
            Path filePath = this.fileStorageLocation.resolve(fileName).normalize();
            Resource resource = new UrlResource(filePath.toUri());
            if (resource.exists()) {
                return resource;
            } else {
                throw new MyFileNotFoundException("File not found " + fileName);
            }
        } catch (MalformedURLException ex) {
            throw new MyFileNotFoundException("File not found " + fileName, ex);
        }
    }
}

上述代码中,我们创建了一个FileStorageService类,用于实现文件存储服务,包含storeFile()和loadFileAsResource()两个方法,其中:

storeFile()方法用于存储上传的文件,可以获取文件的输入流,将文件存储到指定的存储目录中;

loadFileAsResource()方法用于加载指定文件的Resource对象,通过提供的文件名获取文件的Resource对象。

注意,我们使用@Autowired注解注入了config.properties中对应的配置文件路径,使其自动配置为文件存储的目录。

结语

通过Spring Boot的文件和存储服务,我们可以轻松实现文件操作、上传、下载和存储等操作,简单高效,可以应用于各类企业级Java应用。希望本文对大家对Spring Boot文件和存储服务的理解和实践有所帮助。

위 내용은 Spring Boot를 통해 파일 및 스토리지 서비스를 구현하는 방법의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.