1. Ali Cloud OSS Settings

  1. Go to Aliyun: www.aliyun.com/?utm_conten…

  2. Enter the Aliyun console

  3. Accessing the OSS Console

  4. A new Bucket

    A Bucket is the storage space of OSS. Before uploading data (such as documents, images, audio and video) to OSS, you need to create a Bucket in an area supported by OSS and upload an unlimited number of objects to the Bucket.

  5. Enter Bucket information

2. Upload the default profile picture

  1. Go to Bucket and create a new directory

  2. Go to the directory and click Upload File

  3. Select file upload

  4. Use the URL of the default avatar as the default value for the database Avatar field

3. Obtain AccessKeys

  1. Access AccessKeys management

  2. Start using the child user AccessKeys

    Ali Cloud provides each account with a global AccessKey, but if the AccessKey is leaked, the user’s access to all products on Ali Cloud will be exposed. Therefore, the AccessKey of sub-users is selected to talk about all access subdivision. Each Ali Cloud business can customize an independent AccessKey.

  3. Creating a User Group

  4. Add user

  5. Add a user to a user group

  6. Assign permissions to user groups

    You can also assign permissions to each user, while generally simple projects only need to assign permissions to user groups.

  7. To obtain the AccessKey

    After obtaining the AccessKey, you need to save it. If it is lost, create a new AccessKey.

4. Configure the OSS environment

  1. Introducing OSS dependencies into services

    <! -- AliCloud Object Storage -->
    <dependency>
        <groupId>com.aliyun.oss</groupId>
        <artifactId>aliyun-sdk-oss</artifactId>
        <version>2.8.3</version>
    </dependency>
    Copy the code
  2. Look at the endpoint

  3. View accessKeyId and Access

    See 3.7

  4. Check the bucketName

  5. Application. Yml of the service adds configuration

# Ali Cloud OSS configuration
aliyun:
  oss:
    file:
      bucketname: postilhub
      endpoint: oss-cn-beijing.aliyuncs.com
      keyid: xxxxxxxxxxxxx
      keysecret: xxxxxxxxxxxxx
      filehost: avatar
Copy the code
  1. Create the constant package in the service

  2. Create a constant configuration class in constant

@Component
public class OSSConstant implements InitializingBean {

    @Value("${aliyun.oss.file.bucketname}")
    private String bucketName;

    @Value("${aliyun.oss.file.endpoint}")
    private String endpoint;

    @Value("${aliyun.oss.file.keyid}")
    private String keyId;

    @Value("${aliyun.oss.file.keysecret}")
    private String keySecret;

    @Value("${aliyun.oss.file.filehost}")
    private String fileHost;

    public static String BUCKET_NAME;

    public static String ENDPOINT;

    public static String ACCESS_KEY_ID;

    public static String ACCESS_KEY_SECRET;

    public static String FILE_HOST;

    // System configuration after reading the configuration file, assigns the contents of the configuration file to the static constant
    @Override
    public void afterPropertiesSet(a) throws Exception {
        BUCKET_NAME = this.bucketName;
        ENDPOINT = this.endpoint;
        ACCESS_KEY_ID = this.keyId;
        ACCESS_KEY_SECRET = this.keySecret;
        FILE_HOST = this.fileHost; }}Copy the code

5. Upload your profile picture

OSS documentation: help.aliyun.com/document_de…

5.1 UserController. Java

@requestParam (” Avatar “) = @requestBody;

When uploading a file using POST, only form-data can be used to upload the file, not Body (Json) in POST.

@apiOperation (value = "upload user profile picture ")
@PostMapping("uploadAvatar")
public Response uploadAvatar(
   @apiParam (name = "avatar", value = "user avatar file ", required = true)
   @RequestParam("avatar") MultipartFile avatar,
   @RequestHeader("Authorization") String token) {
   // Get the user ID from the Token
   DecodedJWT decodedJWT = JWTUtils.verifyToken(token);
   String id = decodedJWT.getClaim("id").asString();

   try {
       String avatarUrl = userService.uploadAvatar(id, avatar);
       return Response.ok().message("Avatar uploaded successfully").data("avatarUrl", avatarUrl);
   } catch (IOException e) {
       throw new AvatarUploadException(ResponseEnum.AVATAR_UPLOAD_ERROR);
    // return Response.error(ResponseEnum.AVATAR_UPLOAD_ERROR);}}Copy the code

5.2 UserService. Java

/** * OSS upload avatar *@paramAvatar avatar files *@paramId User ID *@returnThe absolute path of the avatar file in the bucket */
String uploadAvatar(String id, MultipartFile avatar) throws IOException;

/** * OSS delete avatar *@param bucketName bucketName
* @paramObjectName Relative path of the profile picture file in bucket */
void deleteAvatar(String bucketName, String objectName);
Copy the code

5.3 UserServiceImpl. Java

@Override
public String uploadAvatar(String id, MultipartFile avatar) throws IOException {

   // Initialize oss parameters
   String bucketName = OSSConstant.BUCKET_NAME;
   String endpoint = OSSConstant.ENDPOINT;
   String accessKeyId = OSSConstant.ACCESS_KEY_ID;
   String accessKeySecret = OSSConstant.ACCESS_KEY_SECRET;
   String fileHost = OSSConstant.FILE_HOST;

   // The address of the avatar file in the network (absolute address on the server)
   String avatarUrl = "";

   // Create an OSSClient instance
   OSSClient ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret);

   // Check whether the bucket exists
   if(! ossClient.doesBucketExist(bucketName)) {// Create buckets using the Aliyun interface
       ossClient.createBucket(bucketName);
       // Set bucket permissions: public read
       ossClient.setBucketAcl(bucketName, CannedAccessControlList.PublicRead);
   }

   // Get the uploaded file stream
   InputStream inputStream = avatar.getInputStream();

   // The name of the original avatar
   String originalAvatarName = avatar.getOriginalFilename();

   // Avatar file type
   String avatarType = originalAvatarName.substring(originalAvatarName.lastIndexOf(".") + 1);

   // Name of the profile picture to upload to bucket
   String avatarName = UUID.randomUUID().toString() + avatarType;

   // The relative path of the avatar file on the bucket (use Jodatime to add a level 3 directory and update a folder every day to improve operation efficiency)
   String avatarRelativePath = fileHost + "/" + new DateTime().toString("yyyy/MM/dd") + "/" + avatarName;

   // Upload the file to bucket
   ossClient.putObject(bucketName, avatarRelativePath, inputStream);

   / / close OSSClient
   ossClient.shutdown();

   / / assembly avatar the absolute path on the bucket: https://bucketName +. + the endpoint/avatarRelativeUrl
   avatarUrl = "https://" + bucketName + "." + endpoint + "/" + avatarRelativePath;

   User user = userMapper.selectById(id);

   // If it is not the first time to upload the profile picture, delete the original profile picture file in bucket
   if(user.getAvatarRelativePath() ! =null) {
       deleteAvatar(bucketName, user.getAvatarRelativePath());
   }

   // Update the absolute and relative paths of the new Avatar to the database
   user.setAvatar(avatarUrl);
   user.setAvatarRelativePath(avatarRelativePath);

   UpdateWrapper<User> updateWrapper = new UpdateWrapper<>();
   updateWrapper.eq("id", id);
   userMapper.update(user, updateWrapper);

   return avatarUrl;
}

@Override
public void deleteAvatar(String bucketName, String objectName) {
   String endpoint = OSSConstant.ENDPOINT;
   String accessKeyId = OSSConstant.ACCESS_KEY_ID;
   String accessKeySecret = OSSConstant.ACCESS_KEY_SECRET;

   OSSClient ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret);

   ossClient.deleteObject(bucketName, objectName);

   ossClient.shutdown();
}
Copy the code