1、进行使用OSS存储图片
利用java实现OSS的上传和下载图片操作,在代码中会开始和关闭使用OSS上传下载图片进行本地存储图片还是OSS存储图片。
2. 首先我们需要将相关的OSS包导入到项目中
<dependency>
<groupId>com.aliyun.oss</groupId>
<artifactId>aliyun-sdk-oss</artifactId>
<version>3.10.2</version>
</dependency>
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.3.1</version>
</dependency>
3.然后我们写相关的实现方法
public static String upLoad(File file,ApplicationProperties applicationProperties) {
if (file == null) {
return null;
}
boolean isImage = true;
try {
Image image = ImageIO.read(file);
isImage = image == null ? false : true;
} catch (IOException e) {
e.printStackTrace();
}
log.info("------OSS文件上传开始--------" + file.getName());
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
String dateStr = format.format(new Date());
OSSClient ossClient = new OSSClient(applicationProperties.getOss().getEndPoint(), applicationProperties.getOss().getAccessKeyId(), applicationProperties.getOss().getAccessKeySecret());
ObjectMetadata objectMetadata = new ObjectMetadata();
objectMetadata.setContentType("image/jpg");
try {
if (!ossClient.doesBucketExist(applicationProperties.getOss().getBucketName())) {
ossClient.createBucket(applicationProperties.getOss().getBucketName());
CreateBucketRequest createBucketRequest = new CreateBucketRequest(applicationProperties.getOss().getBucketName());
createBucketRequest.setCannedACL(CannedAccessControlList.PublicRead);
ossClient.createBucket(createBucketRequest);
}
String fileUrl = applicationProperties.getOss().getFileHost() + "/" + (dateStr + "/" + UUID.randomUUID().toString().replace("-", "") + "-" + file.getName());
if (isImage) {
FILE_URL = fileUrl;
} else {
FILE_URL = "非图片,不可预览。文件路径为:" + fileUrl;
}
ossClient.setBucketAcl(applicationProperties.getOss().getBucketName(), CannedAccessControlList.PublicRead);
PutObjectResult result = ossClient.putObject(new PutObjectRequest(applicationProperties.getOss().getBucketName(), fileUrl, file, objectMetadata));
if (result != null) {
log.info("------OSS文件上传成功------" + fileUrl);
}
} catch (OSSException oe) {
log.error(oe.getMessage());
} catch (ClientException ce) {
log.error(ce.getErrorMessage());
} finally {
ossClient.shutdown();
}
return FILE_URL;
}
public static void writeBytes(String filePath, OutputStream os,ApplicationProperties applicationProperties) throws IOException {
OSSClient ossClient = new OSSClient(applicationProperties.getOss().getEndPoint(), applicationProperties.getOss().getAccessKeyId(), applicationProperties.getOss().getAccessKeySecret());
try {
log.info("------OSS文件下载请求------" + filePath);
OSSObject object = ossClient.getObject(applicationProperties.getOss().getBucketName(), filePath);
if (object == null) {
throw new FileNotFoundException(filePath);
}
try (InputStream fis = object.getObjectContent()) {
byte[] b = new byte[1024];
int length;
while ((length = fis.read(b)) > 0) {
os.write(b, 0, length);
}
log.info("------OSS文件下载成功------" + filePath);
}
} catch (IOException e) {
log.error(e.getMessage(), e);
throw e;
} finally {
if (os != null) {
try {
os.close();
ossClient.shutdown();
} catch (IOException e1) {
log.error(e1.getMessage(), e1);
}
}
}
}
4. 控制层进行请求
@PostMapping("/common/upload")
@ResponseBody
@ApiOperation(value = "图片上传")
public R uploadFileOss(MultipartFile file) {
if (file == null) {
return R.error("请确认上传文件不为空!");
}
String filename = file.getOriginalFilename();
try {
if (applicationProperties.getOss().isEnabled()) {
if (!"".equals(filename.trim())) {
File newFile = new File(filename);
String uploadUrl = OssUtil.upLoad(newFile, applicationProperties);
R ajax = R.success();
ajax.put("fileName", uploadUrl);
return R.success(ajax);
}
} else {
String filePath = Global.getUploadPath();
String fileName = FileUploadUtils.upload(filePath, file);
R ajax = R.success();
ajax.put("fileName", fileName);
return ajax;
}
} catch (Exception ex) {
ex.printStackTrace();
throw new BadRequestAlertException("file upload fail", ENTITY_NAME, FILE_UPLOAD_FAIL);
}
return null;
}
@GetMapping("/common/download")
@ApiOperation(value = "图片预览接口, 此链接单独配置以后可能会被静态资源服务器取代")
@ApiImplicitParams({
@ApiImplicitParam(name = "fileName", value = "文件名", required = true),
})
public void fileDownloadOss(@RequestParam(required = true) String fileName, HttpServletResponse response) {
try {
if (StringUtils.isEmpty(fileName)) {
throw new BusinessException("空的文件名");
}
response.setCharacterEncoding(CharsetKit.UTF8);
response.setContentType("image/jpeg");
if (applicationProperties.getOss().isEnabled()) {
OssUtil.writeBytes(fileName, response.getOutputStream(), applicationProperties);
} else {
}
} catch (Exception e) {
log.error("下载文件失败", e);
}
}