首先在application.yml中配置相关信息
# oss配置
oss:
endpoint: oss-cn-hangzhou.aliyuncs.com
accessKeyId: LTAI5tHmWEh4nWZD*******
accessKeySecret: 5dywdOaBWzNsGXUvv0*******
bucketName: monian-web-tlias
baseURL: https://monian-web-tlias.oss-cn-hangzhou.aliyuncs.com/
在OSSUtils类中注入相关属性:
import com.aliyun.oss.ClientException;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.OSSException;
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.util.UUID;
@Component
@Data
@ConfigurationProperties(prefix = "oss")
public class OSSUtil {
private String endpoint ;
private String accessKeyId ;
private String accessKeySecret ;
private String bucketName ;
private String baseURL ;
public String upload(byte[] dataAy,String extendName) throws IOException {
//创建 OSS对象
OSS client = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
try {
//上传oss 文件夹
final String keySuffixWithSlash = "goods-pic/"+ UUID.randomUUID().toString()+"."+extendName;
client.putObject(bucketName, keySuffixWithSlash, new ByteArrayInputStream(dataAy));
System.out.println("Creating an empty folder " + keySuffixWithSlash + "\n");
return baseURL+keySuffixWithSlash ;
} 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 (ClientException 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 {
/*
* Do not forget to shut down the client finally to release all allocated resources.
*/
client.shutdown();
}
return "" ;
}
}
调用工具类进行图片的上传;
@Api(tags = "商品图片表接口")
@RestController
@RequestMapping("")
public class GoodsPicsController {
@Resource
protected OSSUtil ossUtil ;
@PostMapping("/file/upload")
public AjaxResult upload(@RequestParam("file") MultipartFile file) throws Exception{
//获取文件后缀+文件名
String oldName = file.getOriginalFilename();
//将后缀加到新的文件名上
String extendName = oldName.substring(oldName.lastIndexOf(".")+1);
// 获取文件的字节
byte[] bytes = file.getBytes();
// 这里可以添加保存文件的代码,例如将文件保存到服务器的指定目录
String fileName = ossUtil.upload(bytes,extendName);
return success("上传成功!",fileName);
}
}