准备工作:
1.申请oss 你会得到 endpoint,accessKeyId,bucketName,accessKeySecret
2.引入oss maven dependency : com.aliyun.oss:aliyun-sdk-oss:jar:2.5.0
3. 创建ossClient
@Bean
public OSSClient createOSSClient() {
OSSClient client = new OSSClient(endpoint, accessKeyId, accessKeySecret);
return client;
}
4.上传文件:
InputStream is=new ByteArrayInputStream(bytes);
logger.info("key 为: " + key+" 对应bucket :"+bucketName);
PutObjectResult result = oSSClient.putObject(bucketName, key, is);
logger.info(JSON.toJSONString(result));
5.下载文件:
// 下载图片
OSSObject oSSObject = oSSClient.getObject(bucketName, fileId);
response.setCharacterEncoding("utf-8");
// 设置返回的文件编码
response.setContentType("image/png;image/gif;image/jpeg;image/bmp");
try {
response.getOutputStream().write(IOUtils.toByteArray(oSSObject.getObjectContent()));
} catch (IOException e) {
logger.error("文件下载出错", e);
throw new CampusGuardException("文件下载出错");
}