JAVA关于文件上传存储的三种常用方法--本地存储、OSS、Minio

一、本地存储

1.配置类

@Configuration
public class CorsConfig implements WebMvcConfigurer {

    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**")
            .allowedOrigins("*")
            .allowCredentials(true)
            .allowedMethods("GET", "POST", "PUT", "DELETE", "OPTIONS")
            .maxAge(3600);
    }
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/upload/**").addResourceLocations("file:upload/");
    }

}
package com.wedu.config;

import com.wedu.modules.sys.oauth2.OAuth2Filter;
import com.wedu.modules.sys.oauth2.OAuth2Realm;
import org.apache.shiro.mgt.SecurityManager;
import org.apache.shiro.spring.LifecycleBeanPostProcessor;
import org.apache.shiro.spring.security.interceptor.AuthorizationAttributeSourceAdvisor;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.servlet.Filter;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;

/**
 * Shiro配置
 *
 * @author wedu
 */
@Configuration
public class ShiroConfig {

    @Bean("securityManager")
    public SecurityManager securityManager(OAuth2Realm oAuth2Realm) {
        DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();
        securityManager.setRealm(oAuth2Realm);
        securityManager.setRememberMeManager(null);
        return securityManager;
    }

    @Bean("shiroFilter")
    public ShiroFilterFactoryBean shiroFilter(SecurityManager securityManager) {
        ShiroFilterFactoryBean shiroFilter = new ShiroFilterFactoryBean();
        shiroFilter.setSecurityManager(securityManager);

        //oauth过滤
        Map<String, Filter> filters = new HashMap<>();
        filters.put("oauth2", new OAuth2Filter());
        shiroFilter.setFilters(filters);

        Map<String, String> filterMap = new LinkedHashMap<>();
        filterMap.put("/webjars/**", "anon");
        filterMap.put("/druid/**", "anon");
        filterMap.put("/upload/**", "anon");
        filterMap.put("/app/**", "anon");
        filterMap.put("/sys/login", "anon");
        filterMap.put("/miniprogram/login/loginByCode", "anon");
        filterMap.put("/swagger/**", "anon");
        filterMap.put("/v2/api-docs", "anon");
        filterMap.put("/swagger-ui.html", "anon");
        filterMap.put("/swagger-resources/**", "anon");
        filterMap.put("/captcha.jpg", "anon");
        filterMap.put("/aaa.txt", "anon");
        filterMap.put("/sys/file/getFile/**", "anon");
        filterMap.put("/**", "oauth2");
        shiroFilter.setFilterChainDefinitionMap(filterMap);

        return shiroFilter;
    }

    @Bean("lifecycleBeanPostProcessor")
    public LifecycleBeanPostProcessor lifecycleBeanPostProcessor() {
        return new LifecycleBeanPostProcessor();
    }

    @Bean
    public AuthorizationAttributeSourceAdvisor authorizationAttributeSourceAdvisor(SecurityManager securityManager) {
        AuthorizationAttributeSourceAdvisor advisor = new AuthorizationAttributeSourceAdvisor();
        advisor.setSecurityManager(securityManager);
        return advisor;
    }

}

2.controller文件

package com.wedu.modules.files.controller;
import cn.hutool.core.io.FileUtil;
//@Value注解是springframework下的注解
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;

import com.wedu.common.utils.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.ServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.net.URLEncoder;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.UUID;

import static org.aspectj.weaver.tools.cache.SimpleCacheFactory.path;

@RestController
@RequestMapping("/local")
public class SysFileController {

//    //将该文件夹的路径赋值给fileUploadPath
//    @Value("C:\\shangchuan\\")
//    private String fileUploadPath;



    /**
     * 文件上传接口
     * @param file
     * @return
     * @throws IOException
     * 对应与前端图片上传路径:http://localhost:8081/file/upload/img
     */
    @PostMapping("/upload")
    public String upload(@RequestParam MultipartFile file, ServletRequest request) throws IOException {
        String avatar = file.getOriginalFilename();

        // 生成UUID
        avatar = UUID.randomUUID().toString().replace("-", "") + avatar.substring(avatar.lastIndexOf("."));

        // 将文件保存到本地
        String avatarUrl = null;

        if (avatar != null) {
            // 生成本地地址,将地址保存到数据库
            avatarUrl = "http://localhost:8080/wedu/upload/" + avatar;
            // 将文件保存到本地地址
            try {
//                files.get(0).transferTo(new File("G:\\IDEA2023\\CatAndDogDiaryBackEnd\\CatAndDogEnd\\src\\main\\resources\\static\\avatar\\" + avatar));
                file.transferTo(new File("D:\\扬州戴尔\\项目书\\allProject\\wedu-git-project\\upload\\" + avatar));
            } catch (IOException e) {
                throw new RuntimeException(e);
            }


        }
        return avatarUrl;

    }}

二.OSS 存储

1.配置类

package com.wedu.config;

import com.wedu.common.properties.AliOssProperties ;
import com.wedu.common.utils.AliOssUtil;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
 
@Configuration
public class OssConfiguration {
 
    @Bean
    @ConditionalOnMissingBean
    public AliOssUtil getAliOssUtil(AliOssProperties aliOssProperties) {
        AliOssUtil aliOssUtil = new AliOssUtil(
                aliOssProperties.getEndpoint(),
                aliOssProperties.getAccessKeyId(),
                aliOssProperties.getAccessKeySecret(),
                aliOssProperties.getBucketName()
                );
        return aliOssUtil;
    }
}

2.配置 application.yml文件加上以下代码:

(xxxx内容自行在OSS平台获取)
#OSS配置
sky:
  alioss:
    access-key-id: xxxxxxxx
    access-key-secret: xxxxxx
    bucket-name: xxxxx
    endpoint: xxxxx

3.controller文件

package com.wedu.modules.files.controller;

import com.wedu.common.utils.AliOssUtil;
import com.wedu.common.utils.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;


import java.io.IOException;
import java.util.UUID;

@RestController
@RequestMapping("/oss")
public class CommonController {
 
    @Autowired
    private AliOssUtil aliOssUtil;
 
    @PostMapping("/upload")
    //请求中要携带上需要上传的文件
    public String saveOss(@RequestParam("file")MultipartFile file) {
        try {
            //            获取原始的文件名
            String originalFilename = file.getOriginalFilename();
            //在oss中存储名字就是UUID + 文件的后缀名
            String objectName = UUID.randomUUID() + originalFilename.substring(originalFilename.lastIndexOf("."));
            String resultURL = aliOssUtil.upload(file.getBytes(), objectName);
            return resultURL;
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
 
}

 三.Minio存储

1.配置类

package com.wedu.config;

import io.minio.MinioClient;

import io.minio.ObjectStat;

import io.minio.PutObjectOptions;

import io.minio.Result;

import io.minio.messages.Bucket;

import io.minio.messages.Item;

import org.apache.tomcat.util.http.fileupload.IOUtils;

import org.springframework.beans.factory.InitializingBean;

import org.springframework.beans.factory.annotation.Value;

import org.springframework.stereotype.Component;

import org.springframework.util.Assert;

import org.springframework.web.multipart.MultipartFile;

import org.springframework.web.util.UriUtils;



import javax.servlet.http.HttpServletResponse;

import java.io.IOException;

import java.io.InputStream;

import java.net.URLEncoder;

import java.nio.charset.StandardCharsets;

import java.util.ArrayList;

import java.util.List;





@Component

public class MinioConfig implements InitializingBean {



    @Value(value = "zengshaoxiang")

    private String bucket;



    @Value(value = "http://127.0.0.1:9000")

    private String host;



    @Value(value = "http://127.0.0.1:9000/zengshaoxiang/")

    private String url;



    @Value(value = "root")

    private String accessKey;



    @Value(value = "1234567890")

    private String secretKey;



    private MinioClient minioClient;



    @Override

    public void afterPropertiesSet() throws Exception {

        Assert.hasText(url, "Minio url 为空");

        Assert.hasText(accessKey, "Minio accessKey为空");

        Assert.hasText(secretKey, "Minio secretKey为空");

        this.minioClient = new MinioClient(this.host, this.accessKey, this.secretKey);

    }







    /**

     * 上传

     */

    public String putObject(MultipartFile multipartFile) throws Exception {

        // bucket 不存在,创建

        if (!minioClient.bucketExists(this.bucket)) {

            minioClient.makeBucket(this.bucket);

        }

        try (InputStream inputStream = multipartFile.getInputStream()) {

            // 上传文件的名称

            String fileName = multipartFile.getOriginalFilename();

            // PutObjectOptions,上传配置(文件大小,内存中文件分片大小)

            PutObjectOptions putObjectOptions = new PutObjectOptions(multipartFile.getSize(), PutObjectOptions.MIN_MULTIPART_SIZE);

            // 文件的ContentType

            putObjectOptions.setContentType(multipartFile.getContentType());

            minioClient.putObject(this.bucket, fileName, inputStream, putObjectOptions);

            // 返回访问路径

            return this.url + UriUtils.encode(fileName, StandardCharsets.UTF_8);

        }

    }



    /**

     * 文件下载

     */

    public void download(String fileName, HttpServletResponse response){

        // 从链接中得到文件名

        InputStream inputStream;

        try {

            MinioClient minioClient = new MinioClient(host, accessKey, secretKey);

            ObjectStat stat = minioClient.statObject(bucket, fileName);

            inputStream = minioClient .getObject(bucket, fileName);

            response.setContentType(stat.contentType());

            response.setCharacterEncoding("UTF-8");

            response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));

            IOUtils.copy(inputStream, response.getOutputStream());

            inputStream.close();

        } catch (Exception e){

            e.printStackTrace();

            System.out.println("有异常:" + e);

        }

    }



    /**

     * 列出所有存储桶名称

     *

     * @return

     * @throws Exception

     */

    public List<String> listBucketNames()

            throws Exception {

        List<Bucket> bucketList = listBuckets();

        List<String> bucketListName = new ArrayList<>();

        for (Bucket bucket : bucketList) {

            bucketListName.add(bucket.name());

        }

        return bucketListName;

    }



    /**

     * 查看所有桶

     *

     * @return

     * @throws Exception

     */

    public List<Bucket> listBuckets()

            throws Exception {

        return minioClient.listBuckets();

    }



    /**

     * 检查存储桶是否存在

     *

     * @param bucketName

     * @return

     * @throws Exception

     */

    public boolean bucketExists(String bucketName) throws Exception {

        boolean flag = minioClient.bucketExists(bucketName);

        if (flag) {

            return true;

        }

        return false;

    }



    /**

     * 创建存储桶

     *

     * @param bucketName

     * @return

     * @throws Exception

     */

    public boolean makeBucket(String bucketName)

            throws Exception {

        boolean flag = bucketExists(bucketName);

        if (!flag) {

            minioClient.makeBucket(bucketName);

            return true;

        } else {

            return false;

        }

    }



    /**

     * 删除桶

     *

     * @param bucketName

     * @return

     * @throws Exception

     */

    public boolean removeBucket(String bucketName)

            throws Exception {

        boolean flag = bucketExists(bucketName);

        if (flag) {

            Iterable<Result<Item>> myObjects = listObjects(bucketName);

            for (Result<Item> result : myObjects) {

                Item item = result.get();

                // 有对象文件,则删除失败

                if (item.size() > 0) {

                    return false;

                }

            }

            // 删除存储桶,注意,只有存储桶为空时才能删除成功。

            minioClient.removeBucket(bucketName);

            flag = bucketExists(bucketName);

            if (!flag) {

                return true;

            }



        }

        return false;

    }



    /**

     * 列出存储桶中的所有对象

     *

     * @param bucketName 存储桶名称

     * @return

     * @throws Exception

     */

    public Iterable<Result<Item>> listObjects(String bucketName) throws Exception {

        boolean flag = bucketExists(bucketName);

        if (flag) {

            return minioClient.listObjects(bucketName);

        }

        return null;

    }



    /**

     * 列出存储桶中的所有对象名称

     *

     * @param bucketName 存储桶名称

     * @return

     * @throws Exception

     */

    public List<String> listObjectNames(String bucketName) throws Exception {

        List<String> listObjectNames = new ArrayList<>();

        boolean flag = bucketExists(bucketName);

        if (flag) {

            Iterable<Result<Item>> myObjects = listObjects(bucketName);

            for (Result<Item> result : myObjects) {

                Item item = result.get();

                listObjectNames.add(item.objectName());

            }

        }

        return listObjectNames;

    }



    /**

     * 删除一个对象

     *

     * @param bucketName 存储桶名称

     * @param objectName 存储桶里的对象名称

     * @throws Exception

     */

    public boolean removeObject(String bucketName, String objectName) throws Exception {

        boolean flag = bucketExists(bucketName);

        if (flag) {

            List<String> objectList = listObjectNames(bucketName);

            for (String s : objectList) {

                if(s.equals(objectName)){

                    minioClient.removeObject(bucketName, objectName);

                    return true;

                }

            }

        }

        return false;

    }



    /**

     * 文件访问路径

     *

     * @param bucketName 存储桶名称

     * @param objectName 存储桶里的对象名称

     * @return

     * @throws Exception

     */

    public String getObjectUrl(String bucketName, String objectName) throws Exception {

        boolean flag = bucketExists(bucketName);

        String url = "";

        if (flag) {

            url = minioClient.getObjectUrl(bucketName, objectName);

        }

        return url;

    }



}

 2.controller文件

package com.wedu.modules.files.controller;

import com.wedu.config.MinioConfig;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;


@RestController
@CrossOrigin
@RequestMapping("/minio")
public class MinioController {

    @Autowired
    MinioConfig minioConfig;

    // 上传
    @PostMapping("/upload")
    public Object upload(@RequestParam("file") MultipartFile multipartFile) throws Exception {
        return this.minioConfig.putObject(multipartFile);
    }
}

  • 3
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Java中使用MinIO OSS上传图片,您可以按照以下步骤进行操作: 1. 首先,确保您在项目中添加了MinIO Java SDK的依赖。您可以在Maven项目的pom.xml文件中添加以下依赖项: ```xml <dependency> <groupId>io.minio</groupId> <artifactId>minio</artifactId> <version>8.0.4</version> </dependency> ``` 2. 在代码中导入必要的类: ```java import io.minio.BucketExistsArgs; import io.minio.MakeBucketArgs; import io.minio.MinioClient; import io.minio.PutObjectArgs; import io.minio.errors.MinioException; ``` 3. 创建MinIO客户端并连接到MinIO服务器: ```java try { MinioClient minioClient = MinioClient.builder() .endpoint("https://play.min.io") // MinIO服务器地址 .credentials("your-access-key", "your-secret-key") // 替换为您的访问密钥和秘密密钥 .build(); } catch (MinioException e) { System.out.println("Error occurred: " + e); e.printStackTrace(); } ``` 4. 检查存储桶是否存在,如果不存在则创建它(如果您已经有一个存储桶,请跳过此步骤): ```java boolean found = minioClient.bucketExists(BucketExistsArgs.builder().bucket("your-bucket-name").build()); if (!found) { minioClient.makeBucket(MakeBucketArgs.builder().bucket("your-bucket-name").build()); } ``` 5. 使用`putObject`方法将图片上传到MinIO服务器: ```java try { minioClient.putObject( PutObjectArgs.builder() .bucket("your-bucket-name") // 替换为您的存储桶名称 .object("your-object-name.jpg") // 替换为您的对象名称(包括文件扩展名) .filename("path/to/your-image.jpg") // 替换为您要上传的图片的本地路径 .build() ); System.out.println("Image uploaded successfully."); } catch (MinioException e) { System.out.println("Error occurred: " + e); e.printStackTrace(); } ``` 请确保将上述代码中的占位符替换为您自己的访问密钥、秘密密钥、存储桶名称、对象名称和本地图片路径。以上代码将图片上传到MinIO服务器中指定的存储桶中。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值