Alibaba cloud oss file upload tool class

Introduction

  • File upload, also known as upload, refers to the process of uploading local pictures, videos, audios and other files to the server, which can be browsed or downloaded by other users.

  • File upload is widely used in projects. We often use the file upload function when we post on Weibo and WeChat Moments.

 front-end code

<form action="#" method="post" enctype="multipart/form-data">
    姓名: <input type="text" name="name"/><br/>
    年龄: <input type="text" name="age"/></br>
    图片: <input type="file" name="image"/><br/><br/>
    <input type="submit" value="提交"/>
</form>

The original form for uploading files requires that the form must have the following three points (three elements of the upload file page):

  • The form must have a file field , which is used to select the file to be uploaded.

  • The form submission method must be POST .

  • The encoding type enctype of the form must be set to multipart/form-data .

If we add enctype="multipart/form-data" , it means that the data we request is multipart, and we can also see the requested data through the browser's developer tools (firefox browser):

backend code

On the server side, if we want to receive uploaded files, we need to use an API provided by Spring that specializes in receiving files: MultipartFile.

import com.itheima.pojo.Result;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import java.io.IOException;

@RestController
public class UploadController {

    @PostMapping("/upload")
    public Result upload(MultipartFile image) throws IOException {
        System.out.println(image.getName)
        return Result.success();
    }
	
}

The uploaded files, in fact, are temporarily stored in the temporary files of the system. We can see it through debug.

local storage

For this image upload function, it is mainly divided into two operations:

  • Select the file, upload the image, upload the image file to the server for storage, and then return the URL for image access.

  • When you click Save, in addition to the basic form data of the page that needs to be submitted to the server, the URL for image access also needs to be submitted to the server.

Code

Let's complete the first part first, saving the uploaded pictures in the local disk directory.

package com.itheima.controller;

import com.itheima.pojo.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.UUID;

@RestController
public class UploadController {

    @Autowired
    private AliOSSUtils aliOSSUtils;

    //上传至本地服务器
    @PostMapping("/upload")
    public Result upload(MultipartFile image) throws IOException {
        //获取原始文件名
        String originalFilename = image.getOriginalFilename();
        //构建新的文件名
        String newFileName = UUID.randomUUID().toString()+originalFilename.substring(originalFilename.lastIndexOf("."));
        //将文件保存在服务器端 E:/images/ 目录下
        image.transferTo(new File("E:/images/"+newFileName));
        return Result.success();
    }
    
}

Common methods of MultipartFile:

getOriginalFilename(): Get the original file name​

getContentType(): Get the type of the file​

getInputStream(): Get the input stream of the file​

getBytes(): Get the byte array of the file

test

You can directly use our prepared file upload page for testing.

configuration

In our test of image upload, we found that sometimes it can be uploaded successfully, but sometimes it cannot be uploaded successfully, and the following error is reported.

 The reason for my error is because: In SpringBoot, when uploading files, the default maximum size of a single file is 1M. If you need to upload a large file, you can configure it in application.properties as follows :

#配置单个文件的最大上传大小
spring.servlet.multipart.max-file-size=10MB

#配置单个请求最大上传大小(一次请求可以上传多个文件)
spring.servlet.multipart.max-request-size=100MB

Alibaba Cloud OSS

introduce

Alibaba Cloud Object Storage OSS (Object Storage Service) is a massive, secure, low-cost, and highly reliable cloud storage service that provides 99.9999999999% (12 nines) of data persistence and 99.995% of data availability. A variety of storage types are available to fully optimize storage costs.

step

 After registering an account, you can log in to Alibaba Cloud:

 Click on the console, and find the object storage OSS service.

 If it is the first visit, you also need to activate the object storage service OSS.

 After activation, you can enter the console of Alibaba Cloud Object Storage.

 Click "Bucket List" on the left, and create a Bucket.

File Upload

Refer to the official SDK and modify it to realize the file upload function.

1). pom.xml

<dependency>
    <groupId>com.aliyun.oss</groupId>
    <artifactId>aliyun-sdk-oss</artifactId>
    <version>3.15.0</version>
</dependency>

2). Test file upload

import org.junit.jupiter.api.Test;
import com.aliyun.oss.ClientException;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.OSSException;
import java.io.FileInputStream;
import java.io.InputStream;

public class AliOssTest {

    @Test
    public void testOss(){
        // Endpoint以华东1(杭州)为例,其它Region请按实际情况填写。
        String endpoint = "********";
        // 阿里云账号AccessKey拥有所有API的访问权限,风险很高。强烈建议您创建并使用RAM用户进行API访问或日常运维,请登录RAM控制台创建RAM用户。
        String accessKeyId = "********";
        String accessKeySecret = "*********";
        // 填写Bucket名称,例如examplebucket。
        String bucketName = "web-397";
        // 填写Object完整路径,完整路径中不能包含Bucket名称,例如exampledir/exampleobject.txt。
        String objectName = "0001.jpg";
        // 填写本地文件的完整路径,例如D:\\localpath\\examplefile.txt。
        // 如果未指定本地路径,则默认从示例程序所属项目对应本地路径中上传文件流。
        String filePath= "C:\\Users\\Administrator\\Pictures\\Saved Pictures\\10.jpg";

        // 创建OSSClient实例。
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);

        try {
            InputStream inputStream = new FileInputStream(filePath);
            // 创建PutObject请求。
            ossClient.putObject(bucketName, objectName, inputStream);
        } catch (OSSException oe) {
            System.out.println("Caught an OSSException, which means your request made it to OSS, "
                    + "but was rejected with an error response for some reason.");
            System.out.println("Error Message:" + oe.getErrorMessage());
            System.out.println("Error Code:" + oe.getErrorCode());
            System.out.println("Request ID:" + oe.getRequestId());
            System.out.println("Host ID:" + oe.getHostId());
        } catch (Exception ce) {
            System.out.println("Caught an ClientException, which means the client encountered "
                    + "a serious internal problem while trying to communicate with OSS, "
                    + "such as not being able to access the network.");
            System.out.println("Error Message:" + ce.getMessage());
        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }
    }
}

In the above code, the content that needs to be replaced is:

  • accessKeyId: Aliyun account AccessKey

  • accessKeySecret: the secret key corresponding to the AccessKey of the Alibaba Cloud account

  • bucketName: Bucket name

  • objectName: object name, the name of the object stored in the Bucket

  • filePath: file path

Case Integration OSS

Introduce Aliyun OSS file upload tool class (transformed from the official SDK

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;
import java.io.*;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

/**
 * 阿里云 OSS 工具类
 */
@Component
public class AliOSSUtils {
    
    private String endpoint = "*************";
    private String accessKeyId = "*************";
    private String accessKeySecret = "*************";
    private String bucketName = "web-397";
	
    /**
     * 实现上传图片到OSS
     */
    public String upload(MultipartFile multipartFile) throws IOException {
        // 获取上传的文件的输入流
        InputStream inputStream = multipartFile.getInputStream();
		
        // 避免文件覆盖
        String fileName = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd-HH-mm-ss")) + multipartFile.getOriginalFilename();
		
        //上传文件到 OSS
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
        ossClient.putObject(bucketName, fileName, inputStream);
		
        //文件访问路径
        String url = endpoint.split("//")[0] + "//" + bucketName + "." + endpoint.split("//")[1] + "/" + fileName;
        
        // 关闭ossClient
        ossClient.shutdown();
        return url;// 把上传到oss的路径返回
    }

}

Upload image function upgrade

Upgrade and transform on the basis of the original UploadController

@RestController
public class UploadController {
	
    @Autowired
    private AliOSSUtils aliOSSUtils;
	
    //上传至本地服务器
    /*@PostMapping("/upload")
    public Result upload(MultipartFile image) throws IOException {
        //获取原始文件名
        String originalFilename = image.getOriginalFilename();
        //构建新的文件名
        String newFileName = UUID.randomUUID().toString()+originalFilename.substring(originalFilename.lastIndexOf("."));
        //将文件保存在服务器端 E:/images/ 目录下
        image.transferTo(new File("E:/images/"+newFileName));
        return Result.success();
    }*/
	
    @PostMapping("/upload")
    public Result upload(MultipartFile image) throws IOException {
        String url = aliOSSUtils.upload(image);
        return Result.success(url);
    }
	
}

test

Guess you like

Origin blog.csdn.net/anyi2351033836/article/details/130420227