SpringBoot e-Commerce project mall (25K + STAR) address: github.com/macrozheng/…

Abstract

In the previous section we talked about using MinIO to build an object storage service. This time we’ll look at how MinIO combines SpringBoot and Vue to implement file storage.

Pre-school preparation

Github standard Star 19K+Star, 10 minutes to build the object storage service!

Used with SpringBoot

Next we will combine SpringBoot to implement a complete image upload and delete operation.

  • Schematic diagram of upload process:

  • Add MinIO dependencies to pom.xml:
<! --MinIO JAVA SDK-->
<dependency>
    <groupId>io.minio</groupId>
    <artifactId>minio</artifactId>
    <version>3.0.10</version>
</dependency>
Copy the code
  • To enable file uploading in SpringBoot, add the following configuration to application.yml:
spring:
  servlet:
    multipart:
      enabled: true # Enable file upload
      max-file-size: 10MB # limit file upload size to 10M
Copy the code
  • Add aMinioControllerThe controller is used to upload and delete files:
/** * Created by macro on 2019/12/25. */
@Api(tags = "MinioController", description = "MinIO Object Storage Management")
@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("File upload")
    @RequestMapping(value = "/upload", method = RequestMethod.POST)
    @ResponseBody
    public CommonResult upload(@RequestParam("file") MultipartFile file) {
        try {
            // Create a MinIO Java client
            MinioClient minioClient = new MinioClient(ENDPOINT, ACCESS_KEY, SECRET_KEY);
            boolean isExist = minioClient.bucketExists(BUCKET_NAME);
            if (isExist) {
                LOGGER.info("Bucket already exists!");
            } else {
                // Create a bucket and set the read-only permission
                minioClient.makeBucket(BUCKET_NAME);
                minioClient.setBucketPolicy(BUCKET_NAME, "*. *", PolicyType.READ_ONLY);
            }
            String filename = file.getOriginalFilename();
            SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
            // Set the name of the storage object
            String objectName = sdf.format(new Date()) + "/" + filename;
            // Use putObject to upload a file to the bucket
            minioClient.putObject(BUCKET_NAME, objectName, file.getInputStream(), file.getContentType());
            LOGGER.info("File uploaded successfully!");
            MinioUploadDto minioUploadDto = new MinioUploadDto();
            minioUploadDto.setName(filename);
            minioUploadDto.setUrl(ENDPOINT + "/" + BUCKET_NAME + "/" + objectName);
            return CommonResult.success(minioUploadDto);
        } catch (Exception e) {
            LOGGER.info("Error uploading: {}!", e.getMessage());
        }
        return CommonResult.failed();
    }

    @ApiOperation("File Deletion")
    @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();
        }
        returnCommonResult.failed(); }}Copy the code
  • Configure the MinIO client in application.yml:
# MinIO object storage configuration
minio:
  endpoint: http://192.168.6.132:9090 #MinIO service address
  bucketName: mall # Bucket name
  accessKey: minioadmin Access key
  secretKey: minioadmin # Access the secret key
Copy the code
  • Start my SpringBoot application, use the Postman interface to access the upload file upload, upload interface address: http://localhost:8080/minio/upload

  • After uploading, we can open MinIO’s management interface to see the uploaded image, or access the image through the returned URL:

  • We can call the delete interface to delete the image, note thatobjectNameValue is the relative path of the picture in the bucket, address of the interface to delete the file:http://localhost:8080/minio/delete

Used with Vue

After the above operation, our SpringBoot application can complete file upload and delete operations, next we combine Vue to realize the front-end upload images to MinIO, taking the code in mall- admin-Web as an example.

  • Our SpringBoot application needs to support cross-domain requests, otherwise the Vue front end will not be able to make interface calls. Let’s add a global cross-domain request configuration:
/** * Global cross-domain configuration * Created by macro on 2019/7/27
@Configuration
public class GlobalCorsConfig {

    /** * filters that allow cross-domain calls */
    @Bean
    public CorsFilter corsFilter(a) {
        CorsConfiguration config = new CorsConfiguration();
        // Allow all domain names to make cross-domain calls
        config.addAllowedOrigin("*");
        // Allow cookies to be sent across
        config.setAllowCredentials(true);
        // Release all original headers
        config.addAllowedHeader("*");
        // Allow all request methods to be invoked across domains
        config.addAllowedMethod("*");
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/ * *", config);
        return newCorsFilter(source); }}Copy the code
  • Mall-admin-web uploads files mainly in singleupload. vue and multiupload. vue. Let’s take the modification of Singleupload. vue as an example.

  • We need to make the old OSS upload compatible with the current MinIO upload by adding three properties to the Vue instance data object:

  • Then according to theuseOssAttribute setel-uploadThe submission address and submission parameters of the upload component:

  • inel-uploadAdd the following code to the hook function before uploading the file. For uploading operations using MinIO, the operation of obtaining the OSS upload policy is not performed.

  • Finally, inel-uploadAdd the following code to the hook function for successful file uploads. For upload operations using MinIO, get the file URL directly from the return result.

  • runmall-admin-webFor the project, use the add function under commodity classification to test the file upload and find that the file can be uploaded successfully and the picture can be displayed normally:

Back-end project address

Github.com/macrozheng/…

Front-end project address

Github.com/macrozheng/…

The public,

Mall project full set of learning tutorials serialized, attention to the public number the first time access.