文档说明
此文档为拉钩Java高薪训练营2期课程学习过程,完成作业的文档。顺便说一句拉钩的课程,整个课程,体系非常全,价格上也是所有培训课程中最便宜的。如果希望构建一个整体的技术视野,非常推荐。
作业要求
使用SpringBoot和OSS实现图片的上传、下载和删除功能, 具体要求如下
- 可以使用postman 发送上传请求 /oss/upload ,实现图片上传到OSS对应的Bucket中
类型检查:必须为 jpg、png 或者 jpeg类型,其它图片类型返回错误提示信息
大小检查:必须小于5M,大于5M时返回错误提示信息
图片名称:生成的文件名,必须保持唯一 - 可以使用postman 发送下载请求 /oss/download,实现图片下载
可以根据图片名进行文件的下载 - 可以使用postman 发送删除请求/oss/delete,实现图片删除
可以根据图片名进行文件的删除
——————————————————————————————————
1、提供资料:说明文档,验证及讲解视频。
2、讲解内容包含:题目分析、实现思路、环境介绍。
—————————————————————————————————-
新建Bucke
项目搭建
- 新建 SpringBoot 项目
- 参考:https://help.aliyun.com/knowledge_detail/48699.html 生成 accesskey
- 在 resource 目录下,新建 aliyun.properties 文件
aliyun.properties
# aliyun.properties
aliyun.endpoint=http://oss-cn-beijing.aliyuncs.com
aliyun.accessKeyId=LTAI4GHJMokRfeEjNbyhdfGQ
aliyun.accessKeySecret=DLjzBiTF1Eb6X7mZdOFBCzCQ6lROkI
aliyun.bucketName=lg-mtest
aliyun.urlPrefix=https://lg-mtest.oss-cn-beijing.aliyuncs.com/
application.properties
server.port=8080
# tomcat 默认上传文件大小不能超过 1M
spring.servlet.multipart.max-file-size=10MB
spring.servlet.multipart.max-request-size=20MB
添加依赖
<dependency>
<groupId>com.aliyun.oss</groupId>
<artifactId>aliyun-sdk-oss</artifactId>
<version>2.8.3</version>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.7</version>
</dependency>
<!-- 时间处理工具包 -->
<dependency>
<groupId>joda-time</groupId>
<artifactId>joda-time</artifactId>
<version>2.9.9</version>
</dependency>
AliyunConfig
@Configuration
// 加载配置文件
@PropertySource("classpath:aliyun.properties")
@ConfigurationProperties(prefix = "aliyun")
public class AliyunConfig {
private String endpoint;
private String accessKeyId;
private String accessKeySecret;
private String bucketName;
private String urlPrefix;
// 生成OSSClient
@Bean
public OSSClient ossClient(){
return new OSSClient(endpoint,accessKeyId,accessKeySecret);
}
// 省略 get set 方法
}
UploadResult
package com.example.demo.bean;
public class UploadResult {
// 文件唯一标识
private String uid;
// 文件名
private String name;
// 状态有:uploading done error removed
private String status;
// 服务端响应内容,如:'{"status": "success"}'
private String response;
}
FileService
package com.example.demo.service;
import com.aliyun.oss.OSSClient;
import com.aliyun.oss.model.OSSObject;
import com.aliyun.oss.model.ObjectMetadata;
import com.example.demo.config.AliyunConfig;
import org.apache.commons.lang3.StringUtils;
import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import com.example.demo.bean.UploadResult;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.*;
@Service
public class FileService {
@Autowired
private AliyunConfig aliyunConfig;
@Autowired
private OSSClient ossClient;
// 允许上传的格式
private static final Set<String> IMAGE_TYPE = new HashSet<>(Arrays.asList(".jpg", ".jpeg", ".png"));
/**
* 文件上传
* @param multipartFile
* @return
*/
public UploadResult upload(MultipartFile multipartFile) {
UploadResult upLoadResult = new UploadResult();
String fileName = multipartFile.getOriginalFilename();
// 校验图片格式
String fileType = fileName.substring(fileName.lastIndexOf(".")).toLowerCase();
if (!IMAGE_TYPE.contains(fileType)) {
upLoadResult.setStatus("error");
upLoadResult.setResponse("illegal media type");
return upLoadResult;
}
// 校验文件大小, 超过 5M 为非法文件
if (multipartFile.getSize()> 5 * 1024 * 1024) {
upLoadResult.setStatus("error");
upLoadResult.setResponse("file too large, file size must below 5M");
return upLoadResult;
}
String filePath = getFilePath(fileName);
try {
ObjectMetadata metadata = new ObjectMetadata();
metadata.addUserMetadata("originName", fileName);
ossClient.putObject(aliyunConfig.getBucketName(), filePath, new ByteArrayInputStream(multipartFile.getBytes()), metadata);
} catch (IOException e) {
e.printStackTrace();
// 上传失败
upLoadResult.setStatus("error");
upLoadResult.setResponse("file upload fail, some thing may be wrong");
return upLoadResult;
}
upLoadResult.setStatus("done");
upLoadResult.setName(aliyunConfig.getUrlPrefix() + filePath);
upLoadResult.setUid(filePath);
return upLoadResult;
}
/**
* 文件下载
* @param url
* @param response
*/
public boolean download(String url, HttpServletResponse response) {
OSSObject object = ossClient.getObject(aliyunConfig.getBucketName(), url);
byte[] buf = new byte[1024];
int len;
try(InputStream in = object.getObjectContent(); ServletOutputStream out = response.getOutputStream()) {
while ((len = in.read(buf)) > 0) {
out.write(buf, 0, len);
}
} catch (IOException e) {
e.printStackTrace();
return false;
}
return true;
}
/**
* 删除文件
* @param url
* @return
*/
public boolean delete(String url) {
ossClient.deleteObject(aliyunConfig.getBucketName(), url);
return true;
}
// 生成不重复的文件路径和文件名
private String getFilePath(String sourceFileName) {
DateTime dateTime = new DateTime();
return "images/" + dateTime.toString("yyyy")
+ "/" + dateTime.toString("MM") + "/"
+ dateTime.toString("dd") + "/" + UUID.randomUUID().toString() + "." +
StringUtils.substringAfterLast(sourceFileName, ".");
}
}
FileController
package com.example.demo.controller;
import com.example.demo.bean.UploadResult;
import com.example.demo.service.FileService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletResponse;
@Controller
@RequestMapping("/oss")
public class FileController {
@Autowired
private FileService fileService;
@PostMapping("/upload")
@ResponseBody
public UploadResult upload(@RequestParam("file") MultipartFile multipartFile) {
return fileService.upload(multipartFile);
}
@RequestMapping("/download")
@ResponseBody
public String download(String url, HttpServletResponse response) {
boolean download = false;
try {
download = fileService.download(url, response);
} catch (Exception e) {
e.printStackTrace();
}
if (download) {
return "download success";
}
return "download failed";
}
@RequestMapping("/delete")
@ResponseBody
public String delete(String url) {
boolean download = fileService.delete(url);
if (download) {
return "delete success";
}
return "delete failed";
}
}