docker 搭建文件本地文件服务器

docker上传服务

链接:https://pan.baidu.com/s/1D4fDkrhBerG8nLO78V7b9g
提取码:f0yj

 

文件上传下载源代码

链接:https://pan.baidu.com/s/12l3saM_QgrkUn5-WYuRNhw
提取码:9ds4

 

docker服务器先下载minio镜像

安装脚本:

#创建映射文件夹
mkdir -p /home/minio/data /home/minio/config
#后台启动镜像
docker run -itd -p 9000:9000 --name minio1 \
  -e "MINIO_ACCESS_KEY=AKIAIOSFODNN7EXAMPLE" \
  -e "MINIO_SECRET_KEY=wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY" \
  -v /home/minio/data:/data \
  -v /home/minio/config:/root/.minio \
  minio/minio server /data

方案一:

启动文件上传项目,按照文件提示进行上传下载

 

方案二:

改造上传下载项目的源代码

①:加入依赖

        <dependency>
            <groupId>io.minio</groupId>
            <artifactId>minio</artifactId>
            <version>8.3.3</version>
        </dependency>
        <dependency>
            <groupId>com.squareup.okhttp3</groupId>
            <artifactId>okhttp</artifactId>
            <version>4.8.1</version>
        </dependency>

②:改造代码;JDK版本1.8/spring 微服务版本:2021.1

添加配置:

#文件服务器地址
minio.host=http://minio文件服务器端口:9000
local.host=http://应用服务器部署ip:网管端口
minio.accessKey=AKIAIOSFODNN7EXAMPLE
minio.secretKey=wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY

把下面代码复制到项目中:

MinoConfig

package net.huansi.hscloud.pingpian.config;

import io.minio.MinioClient;
import net.huansi.hscloud.pingpian.property.MinioProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.annotation.Resource;

/**
 * @author falcon
 * @version 1.0.0
 * @ClassName MinoConfig
 * @Description TODO
 * @createTime 2021年11月11日 09:21:00
 */
@Configuration
public class MinoConfig {

    @Resource
    private MinioProperties minioProperties;

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

}
View Code

MinioUtil

package net.huansi.hscloud.pingpian.utils;

import io.minio.*;
import net.huansi.hscloud.common.core.utils.StringUtils;
import net.huansi.hscloud.common.core.utils.file.MimeTypeUtils;
import net.huansi.hscloud.pingpian.common.Constant;
import org.apache.commons.io.FilenameUtils;
import org.apache.tomcat.util.http.fileupload.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
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 falcon
 * @version 1.0.0
 * @ClassName MinioUtil
 * @Description TODO
 * @createTime 2021年11月11日 09:01:00
 */
@Component
public class MinioUtil {

    @Autowired
    private MinioClient minioClient;

    @Value("${minio.host}")
    public String host;

    @Value("${local.host}")
    public String localhost;

    /**
     * 文件上传
     *
     * @param file 要上传的文件
     * @return
     */
    public String upload(MultipartFile file,String bucket) {
        if (null != file) {
            try {
                UUID uuid = UUID.randomUUID();
                StringBuilder s = new StringBuilder();
                s.append(uuid.toString().replace("-", "")).append("/");

                // bucket 不存在,创建
                if (!minioClient.bucketExists(BucketExistsArgs.builder().bucket(bucket).build())) {
                    minioClient.makeBucket(MakeBucketArgs.builder().bucket(bucket).build());
                }
                //得到文件流
                InputStream input = file.getInputStream();

                //文件名
                //String fileName = uuid + "/images." + FilenameUtils.getExtension(file.getOriginalFilename());
//                String fileName = s.append(file.getOriginalFilename()).toString();
                String fileName = Long.toString(Constant.IDWORKER.nextId());
                //拓展名
                String extension = getExtension(file);
                fileName += ("." + extension);
                fileName = s.append(fileName).toString();
                //类型
                String contentType = file.getContentType();
                //把文件放置Minio桶(文件夹)
                // 如需要将文件分成文件夹的形式,只需在文件名前加入对应的文件夹路径就行了
                // 如:fileName = "images/" + fileName;
                ObjectWriteResponse objectWriteResponse = minioClient.putObject(
                        PutObjectArgs.builder().bucket(bucket).object(fileName).stream(
                                        input, -1, 10485760)
                                .contentType(contentType)
                                .build());


                /*if (ProfileEnum.PROD.getCode().equals(SpringUtils.getActiveProfile())) {
                    url = url.replace(minioProperties.getHost(), minioProperties.getAliasName());
                }*/
                return localhost + "/pp/download/" + bucket + "/" + fileName;
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return null;
    }
    public String upload(File file, String bucket) {
        if (null != file) {
            try {
                UUID uuid = UUID.randomUUID();
                StringBuilder s = new StringBuilder();
                s.append(uuid.toString().replace("-", "")).append("/");

                // bucket 不存在,创建
                if (!minioClient.bucketExists(BucketExistsArgs.builder().bucket(bucket).build())) {
                    minioClient.makeBucket(MakeBucketArgs.builder().bucket(bucket).build());
                }
                //得到文件流
                InputStream input = new FileInputStream(file);

                //文件名
                //String fileName = uuid + "/images." + FilenameUtils.getExtension(file.getOriginalFilename());
                String fileName = s.append(file.getName()).toString();
                //类型
                //String contentType = file.getContentType();
                //把文件放置Minio桶(文件夹)
                // 如需要将文件分成文件夹的形式,只需在文件名前加入对应的文件夹路径就行了
                // 如:fileName = "images/" + fileName;
                ObjectWriteResponse objectWriteResponse = minioClient.putObject(
                        PutObjectArgs.builder().bucket(bucket).object(fileName).stream(
                                        input, -1, 10485760)
                                // .contentType(contentType)
                                .build());


                /*if (ProfileEnum.PROD.getCode().equals(SpringUtils.getActiveProfile())) {
                    url = url.replace(minioProperties.getHost(), minioProperties.getAliasName());
                }*/
                return host+"/"+bucket+"/"+fileName;
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return null;
    }
    /**
     * 文件下载
     *
     * @param response
     * @param url
     */
    public void download(HttpServletResponse response, String url,String bucket) {
        // 从链接中得到文件名
        String replace = url.replace(bucket + "/", "#");
        String fileName = replace.split("#")[1];
        InputStream inputStream;
        try {

            StatObjectResponse statObjectResponse = minioClient.statObject(StatObjectArgs.builder().bucket(bucket).object(fileName).build());
            inputStream = minioClient.getObject(GetObjectArgs.builder().bucket(bucket).object(fileName).build());
            response.setContentType(statObjectResponse.contentType());
            response.setCharacterEncoding("UTF-8");
            response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));
            FileOutputStream fileOutputStream = new FileOutputStream(new File("D:\\huansi\\tem\\fileCenter\\src\\test\\java\\net\\huansi\\filecenter"));
            IOUtils.copy(inputStream,fileOutputStream);
            //IOUtils.copy(inputStream, response.getOutputStream());
            inputStream.close();
        } catch (Exception e) {
            e.printStackTrace();
        }

    }
    public void downloads(HttpServletResponse httpServletResponse, String bucket,String dir,String fileName) {
        // 从链接中得到文件名
//        String fullUrl = host + url;
//        String replace = fullUrl.replace(bucket + "/", "#");
//        String fileName = replace.split("#")[1];
        String fileUrl = dir + "/" + fileName;
        InputStream inputStream = null;
        try {
            StatObjectResponse statObjectResponse = minioClient.statObject(StatObjectArgs.builder().bucket(bucket).object(fileUrl).build());
            inputStream = minioClient.getObject(GetObjectArgs.builder().bucket(bucket).object(fileUrl).build());
//            FileOutputStream fileOutputStream = new FileOutputStream(new File("D:/130002.jpg"));
//            IOUtils.copy(inputStream,fileOutputStream);
            //IOUtils.copy(inputStream, response.getOutputStream());

            OutputStream out = null;
            byte[] buf = new byte[1024];
            int legth = 0;
            try {
                out = httpServletResponse.getOutputStream();
                while ((legth = inputStream.read(buf)) != -1) {
                    out.write(buf, 0, legth);
                }
            } finally {
                if (inputStream != null) {
                    inputStream.close();
                }
                if (out != null) {
                    out.close();
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    /**
     * 文件下载
     *
     * @param response
     * @param url
     */
    public byte[] getBytes(HttpServletResponse response, String url,String bucket) {
        // 从链接中得到文件名
        String replace = url.replace(bucket + "/", "#");
        String fileName = replace.split("#")[1];
        InputStream inputStream;
        byte[] bytes = new byte[0];
        try {

            inputStream = minioClient.getObject(GetObjectArgs.builder().bucket(bucket).object(fileName).build());
            bytes = toByteArray(inputStream);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return bytes;
    }

    public static byte[] toByteArray(InputStream input) throws IOException {
        ByteArrayOutputStream output = new ByteArrayOutputStream();
        byte[] buffer = new byte[4096];
        int n = 0;
        while (-1 != (n = input.read(buffer))) {
            output.write(buffer, 0, n);
        }
        return output.toByteArray();
    }

    /**
     * 获取文件名的后缀
     *
     * @param file 表单文件
     * @return 后缀名
     */
    public static String getExtension(MultipartFile file) {
        String extension = FilenameUtils.getExtension(file.getOriginalFilename());
        if (StringUtils.isEmpty(extension)) {
            extension = MimeTypeUtils.getExtension(file.getContentType());
        }
        return extension;
    }
}
View Code

MinioProperties

package net.huansi.hscloud.pingpian.property;

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

/**
 * @author falcon
 * @version 1.0.0
 * @ClassName MinioProperties
 * @Description TODO
 * @createTime 2021年11月11日 09:00:00
 */
@Data
@ConfigurationProperties(prefix = "minio")
@Component
public class MinioProperties {

    private String host;

    private String accessKey;

    private String secretKey;
}
View Code

FileController

package net.huansi.hscloud.pingpian.controller;


import net.huansi.hscloud.pingpian.utils.MinioUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;

/**
 * @author falcon
 * @version 1.0.0
 * @ClassName FIleController
 * @Description TODO
 * @createTime 2021年11月11日 09:43:00
 */
@RestController
public class FileController {

    @Autowired
    private MinioUtil minioUtil;

    @RequestMapping("/upload")
    public String upload(HttpServletRequest request) {
        StringBuilder upload = new StringBuilder();
        List<MultipartFile> files = ((MultipartHttpServletRequest) request).getFiles("file");
        String bucket = request.getParameter("bucket");
        for (MultipartFile file : files) {
            upload.append(minioUtil.upload(file, bucket) + ",");
        }

        if (upload.length() > 0) {
            upload.deleteCharAt(upload.length() - 1);
        }

        return upload.toString();
    }

    @RequestMapping("/download/{bucket}/{dir}/{fileName}")
    public void download(HttpServletResponse response, @PathVariable String bucket, @PathVariable String dir, @PathVariable String fileName) {
        minioUtil.downloads(response, bucket, dir, fileName);
    }
}
View Code

代码使用示例:

 

posted @ 2021-11-19 15:37  流年如水烟雨随风  阅读(1481)  评论(0编辑  收藏  举报