Java上传图片到阿里云OSS
一、pom中引入阿里云sdk<!-- aliYun OSS --><dependency><groupId>com.aliyun.oss</groupId><artifactId>aliyun-sdk-oss</artifactId><version>3.10.2</version></de
·
一、pom中引入阿里云sdk
<!-- aliYun OSS -->
<dependency>
<groupId>com.aliyun.oss</groupId>
<artifactId>aliyun-sdk-oss</artifactId>
<version>3.10.2</version>
</dependency>
二、上传文件接口
public Result buildPosters(MultipartFile imageFile,HttpServletRequest request, HttpServletResponse response) throws IOException {
// 0、上传参数不完整
if (imageFile == null) {
return ResultUtil.ERROR(ResultCode.UPLOAD_PARAM_ERROR);
}
// 1、上传图片规格是否太大
if (imageFile.getSize() >= 5 * 1024 * 1024) {
return ResultUtil.OTHER(ResultCode.IMG_TOO_BIG);
}
// 2、上传
OSS ossClient = new OSSClientBuilder().build("endpoint","accessKeyId", "secretAccessKey");
// 上传的文件名称
String keyUrl = "images/"+imageFile.getName()+".jpg";
InputStream inputStream = imageFile.getInputStream();
ossClient.putObject("bucketName", keyUrl, inputStream);
return ResultUtil.SUCCESS();
}
具体捕获异常进行处理根据当前项目
三、补充上传的文件处理,将文件各种格式转换成文件流
`一、MultipartFile imageFile`
InputStream inputStream = imageFile.getInputStream();
`二、byte[] s`
InputStream inputStream = new ByteArrayInputStream(s);
`三、String imgStr;`
byte[] decode = Base64.getDecoder().decode(imgStr);
InputStream inputStream = new ByteArrayInputStream(decode);
四、文件图片回显
// 图片字节流数组
byte[] decode = Base64.getDecoder().decode(imgStr);
// 字节数组输出流对象
ByteArrayOutputStream output=new ByteArrayOutputStream();
// 字节流数组写到对象中
output.write(decode);
// 获取Servlet输出流对象(响应)
ServletOutputStream out=response.getOutputStream();
// 写到Servlet输出流对象
output.writeTo(out);
魔乐社区(Modelers.cn) 是一个中立、公益的人工智能社区,提供人工智能工具、模型、数据的托管、展示与应用协同服务,为人工智能开发及爱好者搭建开放的学习交流平台。社区通过理事会方式运作,由全产业链共同建设、共同运营、共同享有,推动国产AI生态繁荣发展。
更多推荐



所有评论(0)