一、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);
本文介绍了如何在项目中使用阿里云OSS SDK进行文件上传,包括参数验证、大文件处理和不同格式转换。重点展示了上传接口实现及异常捕获,同时涉及了图片字节流的显示技巧。
3532

被折叠的 条评论
为什么被折叠?



