import com.aliyun.oss.ClientException;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.OSSException;
import com.p.edu.service.OssService;
import com.p.edu.utils.PropertiesUtils;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
@Service
public class OssServiceImpl implements OssService {
@Override
public String OssFileUpload(MultipartFile file) {
// Endpoint以华东1(杭州)为例,其它Region请按实际情况填写。
String endpoint = PropertiesUtils.END_POINT;
// 阿里云账号AccessKey拥有所有API的访问权限,风险很高。强烈建议您创建并使用RAM用户进行API访问或日常运维,请登录RAM控制台创建RAM用户。
String accessKeyId = PropertiesUtils.ACCESS_KEY_ID;
String accessKeySecret = PropertiesUtils.ACCESS_KEY_SECRET;
// 填写Bucket名称,例如examplebucket。
String bucketName = PropertiesUtils.BUCKET_NAME;
//获取文件名字
String objectName = file.getOriginalFilename();
String uuid = UUID.randomUUID().toString().replaceAll("-", "");//防止文件名字重复覆盖
Date date=new Date();
SimpleDateFormat dateFormat=new SimpleDateFormat("yyyy/MM/dd");//添加文件上传路径2019/1/1/791.png
String format = dateFormat.format(date);
objectName=format+uuid+objectName;
// 创建OSSClient实例。
OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
try {
InputStream inputStream =file.getInputStream();//上传文件输入流
// 创建PutObject请求。
//Bucket名称,上传到oss文件路径和文件名称,上传文件输入流
ossClient.putObject(bucketName, objectName, inputStream);
//上传好返回oss路径"https://edu-guli791.oss-cn-hangzhou.aliyuncs.com/"
return "https://"+bucketName+"."+endpoint+"/"+objectName;
} 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());
} catch (IOException e) {
e.printStackTrace();
} finally{
if (ossClient != null) {
ossClient.shutdown();
}
}
return null;
}
}
12-22
965
![](https://csdnimg.cn/release/blogv2/dist/pc/img/readCountWhite.png)
08-19
1379
![](https://csdnimg.cn/release/blogv2/dist/pc/img/readCountWhite.png)
04-30
6827
![](https://csdnimg.cn/release/blogv2/dist/pc/img/readCountWhite.png)
10-11
“相关推荐”对你有帮助么?
-
非常没帮助
-
没帮助
-
一般
-
有帮助
-
非常有帮助
提交