SpringBoot 上传下载文件

一、本地服务器上传下载

1. pom.xml

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
    <version>2.6.3</version>
</dependency>
<dependency>
    <groupId>commons-io</groupId>
    <artifactId>commons-io</artifactId>
    <version>2.15.0</version>
</dependency>

2. application.yml

spring:
  servlet:
    multipart:
      max-request-size: 500MB
      max-file-size: 500MB

3. 创建接口类

import org.apache.commons.io.FileUtils;
import org.springframework.http.ContentDisposition;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RequestPart;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;

@RestController
public class FileController {

    /**
     * 文件上传到服务器
     */
    @PostMapping(value = "/upload", produces = MediaType.APPLICATION_JSON_VALUE)
    public void upload(@RequestPart("file") MultipartFile file) {
        try {
            String filePath = "d:/" + file.getOriginalFilename();
            File writeFile = new File(filePath);
            FileUtils.copyInputStreamToFile(file.getInputStream(), writeFile);
            // TODO: 文件上传后自定义处理
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


    /**
     * 本地文件下载到客户端
     */
    @PostMapping(value = "/down", produces = MediaType.APPLICATION_JSON_VALUE)
    public void down(@RequestParam("fileName") String fileName, HttpServletResponse response) {

        // TODO: 文件在服务器中的绝对路径
        String filePath = "d:/" + fileName;
        try (InputStream inputStream = new FileInputStream(filePath); ServletOutputStream outputStream = response.getOutputStream();) {
            response.reset();
            response.addHeader("Content-Type", MediaType.APPLICATION_OCTET_STREAM_VALUE);
            ContentDisposition disposition = ContentDisposition.builder("attachment")
                    .filename(new String(URLEncoder.encode(fileName, "UTF-8")
                            .getBytes(StandardCharsets.UTF_8), StandardCharsets.ISO_8859_1)).build();
            response.addHeader("Content-Disposition", disposition.toString());

            byte[] buffer = new byte[1024];
            int len;
            while ((len = inputStream.read(buffer)) != -1) {
                outputStream.write(buffer, 0, len);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    /**
     * 网络文件下载到客户端
     */
    @PostMapping(value = "/netDown", produces = MediaType.APPLICATION_JSON_VALUE)
    public void netDown(@RequestParam("net") String net, @RequestParam("fileName") String fileName, HttpServletResponse response) {
        InputStream inputStream = null;
        ServletOutputStream outputStream = null;
        try {
            URL url = new URL(net);
            URLConnection connection = url.openConnection();
            inputStream = connection.getInputStream();
            response.reset();

            response.addHeader("Content-Type", connection.getContentType());
            ContentDisposition disposition = ContentDisposition.builder("attachment")
                    .filename(new String(URLEncoder.encode(fileName, "UTF-8")
                            .getBytes(StandardCharsets.UTF_8), StandardCharsets.ISO_8859_1)).build();
            response.addHeader("Content-Disposition", disposition.toString());

            outputStream = response.getOutputStream();
            byte[] buffer = new byte[1024];
            int len;
            while ((len = inputStream.read(buffer)) != -1) {
                outputStream.write(buffer, 0, len);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (inputStream != null) {
                    inputStream.close();
                }
                if (outputStream != null) {
                    outputStream.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

二、Minio 上传下载

1. pom.xml

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
    <version>3.2.6</version>
</dependency>
<dependency>
    <groupId>org.projectlombok</groupId>
    <artifactId>lombok</artifactId>
    <version>1.18.34</version>
</dependency>
<dependency>
    <groupId>io.minio</groupId>
    <artifactId>minio</artifactId>
    <version>8.2.2</version>
    <exclusions>
        <exclusion>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-databind</artifactId>
        </exclusion>
        <exclusion>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-core</artifactId>
        </exclusion>
    </exclusions>
</dependency>
<dependency>
    <groupId>org.apache.commons</groupId>
    <artifactId>commons-lang3</artifactId>
    <version>3.14.0</version>
</dependency>

2. application.yml

server:
  port: 8888

minio:
  # 对象存储服务的 URL
  endpoint: http://127.0.0.1:9001/
  # 用户名
  accessKey: admin
  # 密码
  secretKey: 12345678
  # 桶名称
  bucketName: test

3. 创建配置类

MinioProperties

import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

/**
 * Minio 参数
 */
@Data
@Component
@ConfigurationProperties(prefix = "minio")
public class MinioProperties {

    /**
     * Minio 连接地址
     */
    private String endpoint;

    /**
     * 用户名
     */
    private String accessKey;

    /**
     * 密码
     */
    private String secretKey;

    /**
     * 桶名称
     */
    private String bucketName;
}

MinioConfig

import io.minio.MinioClient;
import jakarta.annotation.Resource;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * Minio 配置类
 */
@Configuration
@EnableConfigurationProperties(MinioProperties.class)
public class MinioConfig {

    @Resource
    private MinioProperties minioProperties;

    @Bean
    public MinioClient minioClient() {
        return MinioClient.builder()
                .endpoint(minioProperties.getEndpoint())
                .credentials(minioProperties.getAccessKey(), minioProperties.getSecretKey())
                .build();
    }
}

4. 创建工具类

MinioUtils

import io.minio.*;
import io.minio.http.Method;
import io.minio.messages.Bucket;
import io.minio.messages.DeleteError;
import io.minio.messages.DeleteObject;
import io.minio.messages.Item;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletResponse;
import org.apache.tomcat.util.http.fileupload.IOUtils;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLEncoder;
import java.util.*;

/**
 * Minio 工具类
 */
@Component
public class MinioUtils {

    @Resource
    private MinioClient minioClient;

    /**
     * 创建 Bucket
     */
    public void createBucket(String bucketName) {
        try {
            if (bucketExists(bucketName)) {
                minioClient.makeBucket(MakeBucketArgs.builder().bucket(bucketName).build());
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    /**
     * 获取全部 bucket
     */
    public List<String> getAllBuckets() {
        List<String> list = null;
        try {
            final List<Bucket> buckets = minioClient.listBuckets();
            list = new ArrayList<>(buckets.size());
            for (Bucket bucket : buckets) {
                list.add(bucket.name());
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return list;
    }


    /**
     * 根据 bucketName 获取信息
     */
    public Optional<Bucket> getBucket(String bucketName) {
        try {
            return minioClient.listBuckets().stream().filter(b -> b.name().equals(bucketName)).findFirst();
        } catch (Exception e) {
            e.printStackTrace();
            return Optional.empty();
        }
    }


    /**
     * 文件上传
     */
    public Map<String, Object> uploadFile(String bucketName, MultipartFile[] file) {
        List<String> orgfileNameList = new ArrayList<>(file.length);
        for (MultipartFile multipartFile : file) {
            String fileName = multipartFile.getOriginalFilename();
            orgfileNameList.add(fileName);
            try {
                InputStream in = multipartFile.getInputStream();
                minioClient.putObject(PutObjectArgs.builder().bucket(bucketName).object(fileName)
                        .stream(in, multipartFile.getSize(), -1).contentType(multipartFile.getContentType())
                        .build());
                in.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        Map<String, Object> data = new HashMap<>();
        data.put("bucketName", bucketName);
        data.put("fileName", orgfileNameList);
        return data;
    }


    /**
     * 获取上传文件的完整路径
     *
     * @param bucketName 桶名称
     * @param fileName   文件名
     */
    public String getPresetObjectUrl(String bucketName, String fileName) {
        // 验证桶是否存在在
        final boolean validationBucket = bucketExists(bucketName);
        if (!validationBucket) {
            return null;
        }
        // 验证文件是否存在
        final boolean validationFileName = doFileNameExist(bucketName, fileName);
        if (!validationFileName) {
            return null;
        }
        String url = null;
        try {
            // 获取桶和文件的完整路径
            url = minioClient.getPresignedObjectUrl(GetPresignedObjectUrlArgs.builder()
                    .bucket(bucketName).object(fileName).method(Method.GET).build());
        } catch (Exception e) {
            e.printStackTrace();
        }
        return url;
    }


    /**
     * 创建文件夹或目录
     *
     * @param bucketName 存储桶
     * @param objectName 目录路径
     */
    public Map<String, String> putDirObject(String bucketName, String objectName) {
        try {
            if (!bucketExists(bucketName)) {
                return null;
            }
            final ObjectWriteResponse response = minioClient.putObject(
                    PutObjectArgs.builder().bucket(bucketName).object(objectName).stream(
                                    new ByteArrayInputStream(new byte[]{}), 0, -1)
                            .build());
            Map<String, String> map = new HashMap<>();
            map.put("etag", response.etag());
            map.put("versionId", response.versionId());
            return map;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }


    /**
     * 判断文件是否存在
     *
     * @param bucketName 存储桶
     * @param objectName 文件夹名称(去掉 /)
     */
    public boolean doFolderExist(String bucketName, String objectName) {
        boolean exist = false;
        try {
            Iterable<Result<Item>> results = minioClient.listObjects(
                    ListObjectsArgs.builder().bucket(bucketName).prefix(objectName).recursive(false).build());
            for (Result<Item> result : results) {
                Item item = result.get();
                if (item.isDir()) {
                    exist = true;
                }
            }
        } catch (Exception e) {
            exist = false;
        }
        return exist;
    }


    /**
     * 文件下载
     */
    public void downloadFile(HttpServletResponse response, String bucketName, String fileName) {
        if (!doFileNameExist(bucketName, fileName)) {
            return;
        }
        InputStream in = null;
        try {
            StatObjectResponse stat = minioClient.statObject(StatObjectArgs.builder().bucket(bucketName).object(fileName).build());
            response.setContentType(stat.contentType());
            response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));
            in = minioClient.getObject(GetObjectArgs.builder().bucket(bucketName).object(fileName).build());
            IOUtils.copy(in, response.getOutputStream());
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (in != null) {
                try {
                    in.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }


    /**
     * 删除文件
     *
     * @param bucketName bucket名称
     * @param fileName   文件名称
     */
    public void deleteFile(String bucketName, String fileName) {
        try {
            minioClient.removeObject(RemoveObjectArgs.builder().bucket(bucketName).object(fileName).build());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    /**
     * 批量文件删除
     *
     * @param bucketName bucket名称
     * @param fileNames  文件名
     */
    public void deleteBatchFile(String bucketName, List<String> fileNames) {
        try {
            List<DeleteObject> objects = new LinkedList<>();
            for (String fileName : fileNames) {
                objects.add(new DeleteObject(fileName));
            }
            Iterable<Result<DeleteError>> results =
                    minioClient.removeObjects(
                            RemoveObjectsArgs.builder().bucket(bucketName).objects(objects).build());
            for (Result<DeleteError> result : results) {
                DeleteError error = result.get();
                System.out.println("删除失败" + error);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    /**
     * 判断文件是否存在
     */
    private boolean doFileNameExist(String bucketName, String fileName) {
        boolean exist = true;
        try {
            minioClient.statObject(StatObjectArgs.builder().bucket(bucketName).object(fileName).build());
        } catch (Exception e) {
            exist = false;
        }
        return exist;
    }


    /**
     * 验证 bucketName 是否存在
     */
    private boolean bucketExists(String bucketName) {
        boolean flag = true;
        try {
            flag = minioClient.bucketExists(BucketExistsArgs.builder().bucket(bucketName).build());
        } catch (Exception e) {
            e.printStackTrace();
        }
        return flag;
    }
}

5. 创建业务类

MinioController

import com.cnbai.utils.MinioUtils;
import io.minio.messages.Bucket;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.List;
import java.util.Map;
import java.util.Optional;

@RestController
public class MinioController {

    @Resource
    private MinioUtils minioUtils;

    /**
     * 创建 Bucket
     */
    @GetMapping("/createBucket")
    public void createBucket(String bucketName) {
        minioUtils.createBucket(bucketName);
    }


    /**
     * 获取全部 Bucket
     */
    @GetMapping("/getAllBuckets")
    public List<String> getAllBuckets() {
        return minioUtils.getAllBuckets();
    }


    /**
     * 根据 bucketName 获取信息
     */
    @GetMapping("/getBucket")
    public Optional<Bucket> getBucket(String bucketName) {
        return minioUtils.getBucket(bucketName);
    }


    /**
     * 判断文件是否存在
     */
    @GetMapping("/doFolderExist")
    public boolean doFolderExist(String bucketName, String fileName) {
        return minioUtils.doFolderExist(bucketName, fileName);
    }


    /**
     * 创建文件夹或目录
     */
    @GetMapping("/putDirObject")
    public Map<String, String> putDirObject(String bucketName, String fileName) {
        return minioUtils.putDirObject(bucketName, fileName);
    }


    /**
     * 上传文件
     */
    @PostMapping("/uploadFiles")
    public Map<String, Object> uploadFiles(String bucketName, @RequestParam(name = "file") MultipartFile[] file) {
        return minioUtils.uploadFile(bucketName, file);
    }


    /**
     * 获取上传文件的完整浏览路径
     */
    @GetMapping("/getPresetObjectUrl")
    public String getPresetObjectUrl(@RequestParam(name = "filename") String filename) {
        return minioUtils.getPresetObjectUrl("test", filename);
    }


    /**
     * 文件下载
     */
    @GetMapping("/downloadFile")
    public void downloadFile(HttpServletResponse response, @RequestParam("fileName") String fileName) {
        minioUtils.downloadFile(response, "test", fileName);
    }


    /**
     * 删除单个文件
     */
    @DeleteMapping("/deleteFile")
    public void deleteFile(String bucketName, String fileName) {
        minioUtils.deleteFile(bucketName, fileName);
    }


    /**
     * 批量删除文件
     */
    @DeleteMapping("/deleteBatchFile")
    public void deleteBatchFile(String bucketName, @RequestParam("fileNames") List<String> fileNames) {
        minioUtils.deleteBatchFile(bucketName, fileNames);
    }
}
  • 8
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值