JAVA关于文件上传存储的三种常用方法--本地存储、OSS、Minio
创始人
2024-11-11 04:05:53
0

一、本地存储

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 filters = new HashMap<>();         filters.put("oauth2", new OAuth2Filter());         shiroFilter.setFilters(filters);          Map 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 listBucketNames()              throws Exception {          List bucketList = listBuckets();          List bucketListName = new ArrayList<>();          for (Bucket bucket : bucketList) {              bucketListName.add(bucket.name());          }          return bucketListName;      }        /**       * 查看所有桶       *       * @return       * @throws Exception       */      public List 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> myObjects = listObjects(bucketName);              for (Result 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> listObjects(String bucketName) throws Exception {          boolean flag = bucketExists(bucketName);          if (flag) {              return minioClient.listObjects(bucketName);          }          return null;      }        /**       * 列出存储桶中的所有对象名称       *       * @param bucketName 存储桶名称       * @return       * @throws Exception       */      public List listObjectNames(String bucketName) throws Exception {          List listObjectNames = new ArrayList<>();          boolean flag = bucketExists(bucketName);          if (flag) {              Iterable> myObjects = listObjects(bucketName);              for (Result 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 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);     } }

相关内容

热门资讯

玩家必备攻略,牛牛金花房卡模式... 人皇大厅是一款非常受欢迎的棋牌游戏,咨询房/卡添加微信:160470940许多玩家在游戏中会购买房卡...
正版授权!微信群里用链接斗牛房... 微信游戏中心:炸金花房卡,添加微信【55051770】,进入游戏中心或相关小程序,搜索“微信炸金花房...
秒懂教程,购买斗牛房卡联系方式... 新众乐牛牛是一款非常受欢迎的棋牌游戏,咨询房/卡添加微信:15984933许多玩家在游戏中会购买房卡...
正版授权!牛牛房卡怎么购买,微... 微信游戏中心:炸金花房卡,添加微信【33903369】,进入游戏中心或相关小程序,搜索“微信炸金花房...
正版授权!微信链接拼三房卡,微... 微信游戏中心:金花房卡,添加微信【8488009】,进入游戏中心或相关小程序,搜索“微信金花房卡”,...
全攻略普及,链接金花房卡怎么购... 大圣大厅是一款非常受欢迎的棋牌游戏,咨询房/卡添加微信:15984933许多玩家在游戏中会购买房卡来...
正版授权!牛牛链接房卡创建房间... 微信游戏中心:牛牛房卡,添加微信【55051770】,进入游戏中心或相关小程序,搜索“微信牛牛房卡”...
一分钟实测分享,牛牛房卡的客服... 乐酷副厅是一款非常受欢迎的棋牌游戏,咨询房/卡添加微信:44346008许多玩家在游戏中会购买房卡来...
正版授权!微信牌九房卡找谁买,... 微信游戏中心:炸金花房卡,添加微信【33903369】,进入游戏中心或相关小程序,搜索“微信炸金花房...
重大通报,微信牛牛链接怎么制作... 新西部是一款非常受欢迎的棋牌游戏,咨询房/卡添加微信:44346008许多玩家在游戏中会购买房卡来享...
正版授权!微信牌九房卡链接,金... 微信游戏中心:牌九房卡,添加微信【8488009】,进入游戏中心或相关小程序,搜索“微信牌九房卡”,...
正版授权!购买牌九房卡联系方式... 微信游戏中心:牌九房卡,添加微信【55051770】,进入游戏中心或相关小程序,搜索“微信牌九房卡”...
终于懂得,牛牛房卡卖家联系方式... 斗牛是一款非常受欢迎的棋牌游戏,咨询房/卡添加微信:86909166许多玩家在游戏中会购买房卡来享受...
正版授权!微信里玩拼三张房卡,... 微信游戏中心:拼三张房卡,添加微信【33903369】,进入游戏中心或相关小程序,搜索“微信拼三张房...
详细房卡教程,微信牛牛链接金花... 微信炸金花是一款非常受欢迎的棋牌游戏,咨询房/卡添加微信:86909166许多玩家在游戏中会购买房卡...
正版授权!如何购买牛牛房卡,炸... 微信游戏中心:炸金花房卡,添加微信【8488009】,进入游戏中心或相关小程序,搜索“微信炸金花房卡...
秒懂教程,金花链接房卡在哪里弄... 微信炸金花是一款非常受欢迎的棋牌游戏,咨询房/卡添加微信:86909166许多玩家在游戏中会购买房卡...
正版授权!微信拼三张房卡去哪里... 微信游戏中心:拼三张房卡,添加微信【55051770】,进入游戏中心或相关小程序,搜索“微信拼三张房...
玩家必备攻略,微信上金花房卡怎... 卡贝大厅是一款非常受欢迎的棋牌游戏,咨询房/卡添加微信:44346008许多玩家在游戏中会购买房卡来...
正版授权!牛牛房间房卡如何买,... 微信游戏中心:牛牛房卡,添加微信【33903369】,进入游戏中心或相关小程序,搜索“微信牛牛房卡”...