SpringBoot implementa la carga y descarga de archivos para compartir notas (proporciona el código fuente de Gitee)

Prólogo: Aquí hay un resumen de las funciones comunes de carga y descarga de archivos en el proyecto SpringBoot actual. Hay tres métodos de descarga comunes y un método de carga. Aquí hay una nota para compartir.

Tabla de contenido

1. dependencia del pompón

Dos, archivo de configuración yml

3. Descarga de archivos

3.1 Utilice el método de descarga proporcionado por Spring Framework

3.2 Descargar como transmisión a través de IOUtils

3.3 Descargar mientras lees

4. Carga de archivos

Cinco, el código completo de la clase de herramienta.

6. Código fuente de Gitee 

7. Resumen


1. dependencia del pompón

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>

Dos, archivo de configuración yml

# Spring配置
spring:
  # 文件上传
  servlet:
    multipart:
      # 单个文件大小
      max-file-size: 10MB
      # 设置总上传的文件大小
      max-request-size: 20MB
server:
  port: 9090

3. Descarga de archivos

3.1 Utilice el método de descarga proporcionado por Spring Framework

clave:

    /**
     * 使用Spring框架自带的下载方式
     * @param filePath
     * @param fileName
     * @return
     */
    public ResponseEntity<Resource> download(String filePath,String fileName) throws Exception {
        fileName = URLEncoder.encode(fileName,"UTF-8");
        File file = new File(filePath);
        if(!file.exists()){
            throw new Exception("文件不存在");
        }
        return ResponseEntity.ok().header(HttpHeaders.CONTENT_DISPOSITION,
                    "attachment; filename=" + fileName ).body(new FileSystemResource(filePath));
    }

capa de solicitud:

@RestController
@RequestMapping("/file")
public class FileController {

    @Autowired
    private FileUtil fileUtil;

    @GetMapping("/spring/download")
    public ResponseEntity<Resource> download() throws Exception {
        String filePath = "D:\\1.jpg";
        String fileName = "Spring框架下载.jpg";
        return fileUtil.download(filePath,fileName);
    }
    
}

Entrada del navegador: http://localhost:9090/file/spring/download 

 

Descarga completa. 

3.2 Descargar como transmisión a través de IOUtils

clave:

    /**
     * 通过IOUtils以流的形式下载
     * @param filePath
     * @param fileName
     * @param response
     */
    public void download(String filePath , String fileName, HttpServletResponse response) throws Exception {
        fileName = URLEncoder.encode(fileName,"UTF-8");
        File file=new File(filePath);
        if(!file.exists()){
            throw new Exception("文件不存在");
        }
        response.setHeader("Content-disposition","attachment;filename="+ fileName);
        FileInputStream fileInputStream = new FileInputStream(file);
        IOUtils.copy(fileInputStream,response.getOutputStream());
        response.flushBuffer();
        fileInputStream.close();
    }

capa de solicitud: 

@RestController
@RequestMapping("/file")
public class FileController {

    @Autowired
    private FileUtil fileUtil;

    @GetMapping("/io/download")
    public void ioDownload(HttpServletResponse response) throws Exception {
        String filePath = "D:\\1.jpg";
        String fileName = "IO下载.jpg";
        fileUtil.download(filePath,fileName,response);
    }
    
}

Acceso al navegador: http://localhost:9090/file/io/download

descarga exitosa. 

3.3 Descargar mientras lees

clave:

    /**
     * 原始的方法,下载一些小文件,边读边下载的
     * @param filePath
     * @param fileName
     * @param response
     * @throws Exception
     */
    public void downloadTinyFile(String filePath,String fileName, HttpServletResponse response)throws Exception{
        File file = new File(filePath);
        fileName = URLEncoder.encode(fileName, "UTF-8");
        if(!file.exists()){
            throw new Exception("文件不存在");
        }
        FileInputStream in = new FileInputStream(file);
        response.setHeader("Content-Disposition", "attachment;filename="+fileName);
        OutputStream out = response.getOutputStream();
        byte[] b = new byte[1024];
        int len = 0;
        while((len = in.read(b))!=-1){
            out.write(b, 0, len);
        }
        out.flush();
        out.close();
        in.close();
    }

capa de solicitud:

@RestController
@RequestMapping("/file")
public class FileController {

    @Autowired
    private FileUtil fileUtil;

    @GetMapping("/tiny/download")
    public void tinyDownload(HttpServletResponse response) throws Exception {
        String filePath = "D:\\1.jpg";
        String fileName = "tiny下载.jpg";
        fileUtil.downloadTinyFile(filePath,fileName,response);
    }

}

Entrada del navegador: http://localhost:9090/file/tiny/download 

 

descarga exitosa.

4. Carga de archivos

Cargar archivos usando MultipartFile

    /**
     * 上传文件
     * @param multipartFile
     * @param storagePath
     * @return
     * @throws Exception
     */
    public String upload(MultipartFile multipartFile, String storagePath) throws Exception{
        if (multipartFile.isEmpty()) {
            throw new Exception("文件不能为空!");
        }
        String originalFilename = multipartFile.getOriginalFilename();
        String newFileName = UUID.randomUUID()+"_"+originalFilename;
        String filePath = storagePath+newFileName;
        File file = new File(filePath);
        if (!file.getParentFile().exists()) {
            file.getParentFile().mkdirs();
        }
        multipartFile.transferTo(file);
        return filePath;
    }

capa de solicitud:

@RestController
@RequestMapping("/file")
public class FileController {

    @Autowired
    private FileUtil fileUtil;

    @PostMapping("/multipart/upload")
    public String download(MultipartFile file) throws Exception {
        String storagePath = "D:\\";
        return fileUtil.upload(file,storagePath);
    }
    
}

Prueba con la herramienta cartero:

Busque este archivo en la unidad D. 

Cinco, el código completo de la clase de herramienta.

package com.example.file.utils;

import org.apache.tomcat.util.http.fileupload.IOUtils;
import org.springframework.core.io.FileSystemResource;
import org.springframework.core.io.Resource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.util.UUID;

/**
 * 文件工具类
 * @author HTT
 */
@Component
public class FileUtil {

    /**
     * 使用Spring框架自带的下载方式
     * @param filePath
     * @param fileName
     * @return
     */
    public ResponseEntity<Resource> download(String filePath,String fileName) throws Exception {
        fileName = URLEncoder.encode(fileName,"UTF-8");
        File file = new File(filePath);
        if(!file.exists()){
            throw new Exception("文件不存在");
        }
        return ResponseEntity.ok().header(HttpHeaders.CONTENT_DISPOSITION,
                    "attachment; filename=" + fileName ).body(new FileSystemResource(filePath));
    }

    /**
     * 通过IOUtils以流的形式下载
     * @param filePath
     * @param fileName
     * @param response
     */
    public void download(String filePath , String fileName, HttpServletResponse response) throws Exception {
        fileName = URLEncoder.encode(fileName,"UTF-8");
        File file=new File(filePath);
        if(!file.exists()){
            throw new Exception("文件不存在");
        }
        response.setHeader("Content-disposition","attachment;filename="+ fileName);
        FileInputStream fileInputStream = new FileInputStream(file);
        IOUtils.copy(fileInputStream,response.getOutputStream());
        response.flushBuffer();
        fileInputStream.close();
    }

    /**
     * 原始的方法,下载一些小文件,边读边下载的
     * @param filePath
     * @param fileName
     * @param response
     * @throws Exception
     */
    public void downloadTinyFile(String filePath,String fileName, HttpServletResponse response)throws Exception{
        File file = new File(filePath);
        fileName = URLEncoder.encode(fileName, "UTF-8");
        if(!file.exists()){
            throw new Exception("文件不存在");
        }
        FileInputStream in = new FileInputStream(file);
        response.setHeader("Content-Disposition", "attachment;filename="+fileName);
        OutputStream out = response.getOutputStream();
        byte[] b = new byte[1024];
        int len = 0;
        while((len = in.read(b))!=-1){
            out.write(b, 0, len);
        }
        out.flush();
        out.close();
        in.close();
    }

    /**
     * 上传文件
     * @param multipartFile
     * @param storagePath
     * @return
     * @throws Exception
     */
    public String upload(MultipartFile multipartFile, String storagePath) throws Exception{
        if (multipartFile.isEmpty()) {
            throw new Exception("文件不能为空!");
        }
        String originalFilename = multipartFile.getOriginalFilename();
        String newFileName = UUID.randomUUID()+"_"+originalFilename;
        String filePath = storagePath+newFileName;
        File file = new File(filePath);
        if (!file.getParentFile().exists()) {
            file.getParentFile().mkdirs();
        }
        multipartFile.transferTo(file);
        return filePath;
    }

}

6. Código fuente de Gitee 

Dirección de la nube de código: SpringBoot implementa la carga y descarga de archivos

7. Resumen

Las anteriores son notas para que SpringBoot implemente funciones de carga y descarga de archivos, que se pueden copiar y usar con un solo clic.

Supongo que te gusta

Origin blog.csdn.net/HJW_233/article/details/132498328
Recomendado
Clasificación