依赖
<dependency>
<groupId>com.aliyun.oss</groupId>
<artifactId>aliyun-sdk-oss</artifactId>
<version>3.16.3</version>
</dependency>
上传示例
package com.fan.model.image;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.fan.entity.vo.ComResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Objects;
@Slf4j
@Controller
public class ImageController {
@RequestMapping("/image/upload")
@ResponseBody
public ComResult<String> uploadImg(@RequestParam("file") MultipartFile file) throws IOException {
if (file.isEmpty()) {
return ComResult.failMsg("文件不能为空");
}
String suffix = Objects.requireNonNull(file.getOriginalFilename()).substring(file.getOriginalFilename().lastIndexOf("."));
if (!suffix.contains("png") && !suffix.contains("jpg") && !suffix.contains("gif")) {
return ComResult.failMsg("仅支持png/jpg/gif图片");
}
String random = String.valueOf((int) (Math.random() * 1000000));
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
String newFileName = sdf.format(new Date());
String name = newFileName + "_" + random;
String endpoint = "https://oss-cn-chengdu.aliyuncs.com";
String accessKeyId = "xxxxxxx";
String accessKeySecret = "xxxxxxx";
OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
String bucketName = "fanmross";
String folderName = "house";
String objectName = folderName + "/" + name + suffix;
ossClient.putObject(bucketName, objectName, file.getInputStream());
ossClient.shutdown();
return ComResult.data("添加成功", endpoint.replace("//", "//" + bucketName + ".") + "/" + objectName);
}
}
地址文档
地域和Endpoint
跨域配置

Etag
x-oss-request-id