Before and after the end of the separation project, how elegant for file storage!

SpringBoot actual electricity supplier item mall (25k + star) Address: github.com/macrozheng/...

Summary

In the previous section we talked about the use MinIO built from object storage service, this time we are speaking under MinIO how to combine SpringBoot and Vue to achieve file storage.

School readiness

This article needs some MinIO learning the basics, do not understand the small partners can refer to the following: Github starred 19K + Star, 10 Fenzhong self-built object storage service!

Use in conjunction SpringBoot

Next we will combine SpringBoot to achieve a complete picture upload and delete operations.

  • Upload flow diagram:

  • Add the relevant dependent MinIO in the pom.xml:
<!--MinIO JAVA SDK-->
<dependency>
    <groupId>io.minio</groupId>
    <artifactId>minio</artifactId>
    <version>3.0.10</version>
</dependency>
复制代码
  • Open the file upload function in SpringBoot, you need to add the following configuration application.yml:
spring:
  servlet:
    multipart:
      enabled: true #开启文件上传
      max-file-size: 10MB #限制文件上传大小为10M
复制代码
  • Adding a MinioControllercontroller is used to upload and delete operations implementation file:
/**
 * Created by macro on 2019/12/25.
 */
@Api(tags = "MinioController", description = "MinIO对象存储管理")
@Controller
@RequestMapping("/minio")
public class MinioController {

    private static final Logger LOGGER = LoggerFactory.getLogger(MinioController.class);
    @Value("${minio.endpoint}")
    private String ENDPOINT;
    @Value("${minio.bucketName}")
    private String BUCKET_NAME;
    @Value("${minio.accessKey}")
    private String ACCESS_KEY;
    @Value("${minio.secretKey}")
    private String SECRET_KEY;

    @ApiOperation("文件上传")
    @RequestMapping(value = "/upload", method = RequestMethod.POST)
    @ResponseBody
    public CommonResult upload(@RequestParam("file") MultipartFile file) {
        try {
            //创建一个MinIO的Java客户端
            MinioClient minioClient = new MinioClient(ENDPOINT, ACCESS_KEY, SECRET_KEY);
            boolean isExist = minioClient.bucketExists(BUCKET_NAME);
            if (isExist) {
                LOGGER.info("存储桶已经存在!");
            } else {
                //创建存储桶并设置只读权限
                minioClient.makeBucket(BUCKET_NAME);
                minioClient.setBucketPolicy(BUCKET_NAME, "*.*", PolicyType.READ_ONLY);
            }
            String filename = file.getOriginalFilename();
            SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
            // 设置存储对象名称
            String objectName = sdf.format(new Date()) + "/" + filename;
            // 使用putObject上传一个文件到存储桶中
            minioClient.putObject(BUCKET_NAME, objectName, file.getInputStream(), file.getContentType());
            LOGGER.info("文件上传成功!");
            MinioUploadDto minioUploadDto = new MinioUploadDto();
            minioUploadDto.setName(filename);
            minioUploadDto.setUrl(ENDPOINT + "/" + BUCKET_NAME + "/" + objectName);
            return CommonResult.success(minioUploadDto);
        } catch (Exception e) {
            LOGGER.info("上传发生错误: {}!", e.getMessage());
        }
        return CommonResult.failed();
    }

    @ApiOperation("文件删除")
    @RequestMapping(value = "/delete", method = RequestMethod.POST)
    @ResponseBody
    public CommonResult delete(@RequestParam("objectName") String objectName) {
        try {
            MinioClient minioClient = new MinioClient(ENDPOINT, ACCESS_KEY, SECRET_KEY);
            minioClient.removeObject(BUCKET_NAME, objectName);
            return CommonResult.success(null);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return CommonResult.failed();
    }
}
复制代码
  • Configure MinIO client application.yml in:
# MinIO对象存储相关配置
minio:
  endpoint: http://192.168.6.132:9090 #MinIO服务所在地址
  bucketName: mall #存储桶名称
  accessKey: minioadmin #访问的key
  secretKey: minioadmin #访问的秘钥
复制代码

  • After uploading, we open MinIO management interface can see the pictures after upload, you can also access the images returned by url:

Use in conjunction with Vue

After the above operation, our SpringBoot application can be completed in a file upload and delete operations, and then we combine Vue to achieve front-end upload images to MinIO in to mall-admin-webthe code as an example.

  • Our SpringBoot applications need to support cross-domain requests otherwise Vue front-end interface calls can not be, let's add a global cross-domain requests configuration:
/**
 * 全局跨域配置
 * Created by macro on 2019/7/27.
 */
@Configuration
public class GlobalCorsConfig {

    /**
     * 允许跨域调用的过滤器
     */
    @Bean
    public CorsFilter corsFilter() {
        CorsConfiguration config = new CorsConfiguration();
        //允许所有域名进行跨域调用
        config.addAllowedOrigin("*");
        //允许跨越发送cookie
        config.setAllowCredentials(true);
        //放行全部原始头信息
        config.addAllowedHeader("*");
        //允许所有请求方法跨域调用
        config.addAllowedMethod("*");
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", config);
        return new CorsFilter(source);
    }
}
复制代码
  • mall-admin-webFile upload operations mainly in singleUpload.vueand multiUpload.vuein the following we singleUpload.vuemodified example.

  • We need the original OSS upload and now MinIO upload operation to be compatible, first add three attributes in a data object Vue instance:

  • Then according to the useOssproperty of the el-uploadsubmitted address and submit the parameters uploaded components:

  • In el-uploadadd the following code before upload hook function for uploading using the operating MinIO not get uploaded OSS operating strategy;

  • Finally, el-uploadadd the following code file upload successfully hook function, file url acquired using MinIO upload operation from the returned results;

  • Run mall-admin-webthe project, use the Add function to test under the classification of goods under the file upload, found to have been successfully uploaded, the picture also can be a normal echo:

The rear end of the project address

github.com/macrozheng/…

Front-end project address

github.com/macrozheng/…

the public

mall project a full tutorial serialized in public concern number the first time to obtain.

No public picture

Guess you like

Origin juejin.im/post/5e0ca2266fb9a0484a45969c