Xiao Er is a new intern. As the technical leader, I arranged a very simple practice task for him, which was to save the pictures uploaded in the front-end Markdown editor to the server. As a result, he saved the pictures directly to the server. Like OSS, MinIO?

He justly and forcefully refuted: “who let you don’t speak clearly, I go to find the boss to fire you!” I immediately lost my nerve and said, “Come on, I’ll show you how to save the image to OSS, ok?”

“No, I’ll teach you.” Xiao 2 is very confident, here is his record of integrating OSS in Spring Boot application.

We hereby declare: ali cloud OSS product responsible person after seeing please consciously come to settle the promotion fee (dog head). Honestly: Spring Boot+OSS is pretty common in real world development.

1. Open OSS

OSS, also known as Object Storage Service, is a set of Object Storage services provided by Ali Cloud. Domestic competitors include Kodo of Qiuniuyun and COS of Tencent Cloud.

Step 1: Log in to the official website of Ali Cloud, search for the keyword “OSS”, and enter the OSS product page.

Step 2, if you are a new USER of OSS, you can enjoy the exclusive price for the new user for 6 months, but it still hurts to renew.

Step 3 go to the OSS administrative Console, click Bucket List, and click Create Bucket.

A Bucket is a container used to store objects. Note The read/write permission is public read, which allows Internet users to access images in the cloud space.

Step 4, click “OK” to be successful.

2. Integration of OSS

The first step is to add OSS dependencies to the POM.xml file.

<! OSS --> <dependency> <groupId>com.aliyun. OSS </groupId> <artifactId> The < version > 3.10.2 < / version > < / dependency >Copy the code

Step 2, add the OSS configuration items to the application.yml file.

Aliyun: OSS: # Access domain name for oss external services endpoint: oss-cn-beijing.aliyuncs.com # accessKeyId: AccessKeySecret: RYN # STORAGE space for OSS bucketName: itwanger- OSs1 # Upload file size (M) maxSize: 3 # Upload folder path prefix dir: prefix: codingmore/images/Copy the code

The third step is to add the ossclientConfig. Java configuration class, which basically uses the @Value annotation to get configuration items from the configuration file and then create OSSClient.

@Configuration
public class OssClientConfig {
    @Value("${aliyun.oss.endpoint}")
    String endpoint ;
    @Value("${aliyun.oss.accessKeyId}")
    String accessKeyId ;
    @Value("${aliyun.oss.accessKeySecret}")
    String accessKeySecret;

    @Bean
    public OSSClient createOssClient(a) {
        return (OSSClient)newOSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret); }}Copy the code

Step 4: Add file upload interface ossController.java and set parameter to MultipartFile.

@Controller
@api (tags = "upload ")
@RequestMapping("/ossController")
public class OssController {
    @Autowired
    private IOssService ossService;

    @RequestMapping(value = "/upload",method=RequestMethod.POST)
    @ResponseBody
    @ ApiOperation (" upload ")
    public ResultObject<String> upload(@RequestParam("file") MultipartFile file, HttpServletRequest req)  {
        returnResultObject.success(ossService.upload(file)); }}Copy the code

Step 5 add a Service to upload the file to OSS and return the file save path.

@Service
public class OssServiceImpl implements IOssService{

    @Value("${aliyun.oss.maxSize}")
    private int maxSize;
   
    @Value("${aliyun.oss.bucketName}")
    private String bucketName;
  
    @Value("${aliyun.oss.dir.prefix}")
    private String dirPrefix;
    
    @Autowired
    private OSSClient ossClient;   
    @Override
    public String upload(MultipartFile file) {
        try {
            return upload(file.getInputStream(), file.getOriginalFilename());
        } catch (IOException e) {
            LOGGER.error(e.getMessage());
        }
        return null;
    }

    @Override
    public String upload(InputStream inputStream,String name) {
        String objectName = getBucketName(name);
        // Create the PutObject request.
        ossClient.putObject(bucketName, objectName, inputStream);
        return formatPath(objectName);
    }
    private String getBucketName(String url){
        String ext = "";
        for(String extItem:imageExtension){
            if(url.indexOf(extItem) ! = -1){
                ext = extItem;
                break; }}return dirPrefix+ DateUtil.today()+"/"+ IdUtil.randomUUID()+ext;
    }

    private String formatPath(String objectName){
        return "https://"  +bucketName+"."+ ossClient.getEndpoint().getHost() + "/"+ objectName; }}Copy the code

Step 6, open the Apipost, test the OSS upload interface, pay attention to the parameter selection file, click send, you can see the picture link returned by the server.

Step 7, enter ali Cloud OSS background management, you can confirm that the picture has been uploaded successfully.

Pull front-end code to test the OSS upload interface

Codingmore-admin-web is a front-end management project for programming Meow (Codingmore), which can be pulled locally from the address below.

Github.com/itwanger/co…

After running the yarn run dev command, you can start the Web management terminal, go to the article editing page, select an image, and upload the image. Ensure that the image can be uploaded from the front end to the server, and the server uploads the image to the OSS, and then return to the front end image access link.

4. Use OSS for automatic translinking

The first step is to add a link transfer method in postsServicePl.java, which uses regular expressions to find links in the content of the article, and then upload the link image to OSS, and replace the original link image.

// Match the markdown syntax of the image
/ /! [](hhhx.png)
/ /! [xx](hhhx.png? ax)
public static final String IMG_PATTERN = "\ \! \ \ \ \ \ \ [*] ((. *) \ \";

private void handleContentImg(Posts posts) {
    String content = posts.getPostContent();

    Pattern p = Pattern.compile(IMG_PATTERN, Pattern.CASE_INSENSITIVE);
    Matcher m = p.matcher(content);

    Map<String, Future<String>> map = new HashMap<>();

    while (m.find()) {
        String imageTag = m.group();
        LOGGER.info("Replace {} with grouping", imageTag);

        String imageUrl = imageTag.substring(imageTag.indexOf("(") + 1, imageTag.indexOf(")"));

        // Confirm that this is a link to this site
        if(imageUrl.indexOf(iOssService.getEndPoint()) ! = -1) {
            continue;
        }

        // Upload images to OSS through thread pools
        Future<String> future = ossUploadImageExecutor.submit(() -> {
            return iOssService.upload(imageUrl);
        });
        map.put(imageUrl, future);
    }

    for (String oldUrl : map.keySet()) {
        Future<String> future = map.get(oldUrl);

        try {
           String imageUrl = future.get();
           content = content.replace(oldUrl, imageUrl);
        } catch (InterruptedException | ExecutionException e) {
            LOGGER.error("Error getting image link {}", e.getMessage());
        }
        
    }
    posts.setPostContent(content);
} 
Copy the code

Second, add a method to upload images to OSS based on the external link address in ossServicePl.java.

public String upload(String url) {
    String objectName = getFileName(url);
    try (InputStream inputStream = new URL(url).openStream()) {
        ossClient.putObject(bucketName, objectName, inputStream);
    } catch (IOException e) {
        LOGGER.error(e.getMessage());
    }
    return formatOSSPath(objectName);
}
Copy the code

The third step, through the Web management end to test whether the chain transfer success. First look for two pictures of the outer chain, you can see that the Markdown is not displayed in the preview.

Then we click Publish and you can see that both images are displayed normally because they are converted to the OSS image access address.

Five, the summary

To sum up, the integration of OSS code in Spring Boot is quite reasonable. Perhaps OSS+CDN is the best solution for map bed, but the problem that aliyun HTTPS CDN cannot be returned to GitHub, resulting in images not being displayed, has not been effectively solved.

Need source partners can go directly to programming meow 🐱 source path pull:

Github.com/itwanger/co…


This post is on GitHub’s 1.8K + Star: The Path to Java Programmer Advancement. It is said that every good Java programmer likes her. The content includes Java foundation, Java concurrent programming, Java virtual machine, Java enterprise development, Java interview and other core knowledge points. Learn Java, look for Java programmers to advance the road 😄.

Github.com/itwanger/to…

Star the repository and you have the potential to become a good Java engineer. Click the link below to jump to the Java Programmer’s Path to Progress website and start your fun learning journey.

tobebetterjavaer.com/

Nothing keeps me here but purpose, and though there are roses by the shore, and trees by the shore, and still harbours, I am not tied.