element-ui,通过springboot,文件上传minio服务器

data.vue

<template>
<el-button  size="small" type="success" :loading="this.load" @click="submitUpload">上传到服务器</el-button>
<el-upload
   class="upload-demo"
   ref="fileUpload"
   action="#"
   :file-list="fileList"
   :multiple="true"
   accept=".xlsx"
   :before-upload="beforeUpload"
   :on-remove="handleRemove"
   :limit="10"
   :auto-upload="false"
   :http-request="httpSub"
   style="margin-top: 10px"
>
   <el-button size="small" type="primary">
     <i class="el-icon-upload el-icon--right"></i>
     上传文件
   </el-button>
</el-upload>
</template>

<script>
import { getFileList} from "@/api/data/data";

export default {
  data() {
    return {
      load:false,
      fileList: [],
      fileOssList:[]
    };
  },
  methods: {
    submitUpload() {
      this.load=true
      this.$refs.fileUpload.submit();
    },
    httpSub(fileList){
      let formData = new FormData();
      formData.append("file", fileList.file);
      formData.append('address', '/file');
      upload(formData).then(result=>{
        if(result.code==1){
          this.$message.error(result.msg)
        }else{
          this.load=false
          this.$message.success("上传成功")
        }
      })
    },
    handleRemove(file,fileList) {
      return fileList.filter(value=>{
        return value!=file
      })
    },
    beforeUpload(file) {
      let regExp = file.name.replace(/.+\./, '');
      let lower = regExp.toLowerCase(); //把大写字符串全部转为小写字符串
      let suffix = ['xls', 'xlsx'];
      if (suffix.indexOf(lower) === -1) {
        return this.$message.warning('请上传后缀名为 xls、xlsx 的附件 !');
      }
      let isLt2M = file.size / 1024 / 1024 < 10;
      if (!isLt2M) {
        return this.$message.error('请上传文件大小不能超过 10MB 的附件 !');
      }
    },
  }
}
</script>

data.js

export function upload(file) {
  return request({
    url: '/data/uploadFile',
    method: 'post',
    data:file,
  })
}

SpringbootController

@RestController
@RequestMapping("/data")
public class MigrateDataController {
   @Autowired
   private FileService fileService;

   @PostMapping(value = "/uploadFile", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
   public R importFile(@RequestParam("file") MultipartFile file, @RequestParam("address") String address){
      Calendar calendar = Calendar.getInstance();
      String fileAddress = calendar.get(Calendar.YEAR) + "/" + (calendar.get(Calendar.MONTH)+1) + "/" + calendar.get(Calendar.DATE) +address+"/";
      R r = fileService.uploadFile(file, fileAddress);
      return r;
   }
}

SpringbootService

@Servic
public class FileServiceImp implements FileService{
   private final String BUCKET_NAME = "桶名";
   private static MinioUtils minioUtils = new MinioUtils("http://xx.xxx.xxx:9000","账号","密码","桶名");
   @Override
   @Transactional(rollbackFor = Exception.class)
   public R uploadFile(MultipartFile file,String fileAddressName) {
      String fileName = file.getOriginalFilename();
      try {
         fileName =new String(file.getOriginalFilename().getBytes("iso-8859-1"),"UTF-8");
      } catch (UnsupportedEncodingException e) {
         e.printStackTrace();
      }
      String allName = fileAddressName+"/"+ fileName;
      Map<String, String> resultMap = new HashMap<>(4);
      resultMap.put("bucketName", BUCKET_NAME);
      resultMap.put("fileName", fileName);
      resultMap.put("url", String.format(fileAddressName));
      try {
         if (!minioUtils.doesFolderExist(BUCKET_NAME,fileAddressName)){

            minioUtils.putDirObject(BUCKET_NAME,fileAddressName);
         }
         if (minioUtils.doesObjectExist(BUCKET_NAME,allName)) {
            return R.failed("文件"+fileName+"已存在");
         }
         minioUtils.putObject(BUCKET_NAME,file,allName,file.getContentType());
      } catch (Exception e) {
         return R.failed(e.getLocalizedMessage());
      }
      return R.ok(resultMap);
   }
}

minioUtils

public class MinioUtils {

   private static MinioClient minioClient;

   private static String endpoint;
   private static String bucketName;
   private static String accessKey;
   private static String secretKey;

   private static final String SEPARATOR = "/";

   private MinioUtils() {
   }

   public MinioUtils(String endpoint, String bucketName, String accessKey, String secretKey) {
      MinioUtils.endpoint = endpoint;
      MinioUtils.bucketName = bucketName;
      MinioUtils.accessKey = accessKey;
      MinioUtils.secretKey = secretKey;
      createMinioClient();

   }
/**
 * 创建minioClient
 */
public void createMinioClient() {
   try {
      if (null == minioClient) {
         log.info("minioClient create start");
         minioClient = MinioClient.builder().endpoint(endpoint).credentials(accessKey, secretKey).build();
         createBucket();
         log.info("minioClient create end");
      }
   } catch (Exception e) {
      log.error("连接MinIO服务器异常:{}", e);
   }
}
/**
 * 判断文件是否存在
 *
 * @param bucketName 存储桶
 * @param objectName 对象
 * @return true:存在
 */
public static boolean doesObjectExist(String bucketName, String objectName) {
   boolean exist = true;
   try {
      minioClient
            .statObject(StatObjectArgs.builder().bucket(bucketName).object(objectName).build());
   } catch (Exception e) {
      exist = false;
   }
   return exist;
}

/**
 * 判断文件夹是否存在
 *
 * @param bucketName 存储桶
 * @param objectName 文件夹名称(去掉/)
 * @return true:存在
 */
public static boolean doesFolderExist(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() && objectName.equals(item.objectName())) {
            exist = true;
         }
      }
   } catch (Exception e) {
      exist = false;
   }
   return exist;
}
/**
 * 获取文件流
 *
 * @param bucketName bucket名称
 * @param objectName 文件名称
 * @return 二进制流
 */
public static InputStream getObject(String bucketName, String objectName)
      throws IOException, InvalidKeyException, InvalidResponseException, InsufficientDataException, NoSuchAlgorithmException, ServerException, InternalException, XmlParserException, ErrorResponseException {
   return minioClient.getObject(GetObjectArgs.builder().bucket(bucketName).object(objectName).build());
}
/**
 * 通过MultipartFile,上传文件
 *
 * @param bucketName 存储桶
 * @param file       文件
 * @param objectName 对象名
 */
public static ObjectWriteResponse putObject(String bucketName, MultipartFile file,
                                 String objectName, String contentType)
      throws IOException, InvalidKeyException, InvalidResponseException, InsufficientDataException, NoSuchAlgorithmException, ServerException, InternalException, XmlParserException, ErrorResponseException {
   InputStream inputStream = file.getInputStream();
   return minioClient.putObject(
         PutObjectArgs.builder().bucket(bucketName).object(objectName).contentType(contentType)
               .stream(
                     inputStream, inputStream.available(), -1)
               .build());
}
/**
 * 创建文件夹或目录
 *
 * @param bucketName 存储桶
 * @param objectName 目录路径
 */
public static ObjectWriteResponse putDirObject(String bucketName, String objectName)
      throws IOException, InvalidKeyException, InvalidResponseException, InsufficientDataException, NoSuchAlgorithmException, ServerException, InternalException, XmlParserException, ErrorResponseException {
   return minioClient.putObject(
         PutObjectArgs.builder().bucket(bucketName).object(objectName).stream(
                     new ByteArrayInputStream(new byte[]{}), 0, -1)
               .build());
}
}
上传文件夹名fileAddressName,文件名fileName
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值