这里介绍两种上传存储方式
com.aliyun.oss
aliyun-sdk-oss
2.8.3
org.projectlombok
lombok
1.18.4
joda-time
joda-time
2.9.9
accessKeyId以及accessKeySecret获取参考官方文档:
https://help.aliyun.com/knowledge_detail/48699.html
@Configuration
@PropertySource("aliyun.properties")
@ConfigurationProperties(prefix = "aliyun")
public class AlyunConfig {
private String endpoint;
private String accessKeyId;
private String accessKeySecret;
private String bucketName;
private String urlPrefix;
@Bean
public OSS oSSClient() {
return new OSSClient(endpoint, accessKeyId, accessKeySecret);
}
public String getEndpoint() {
return endpoint;
}
public void setEndpoint(String endpoint) {
this.endpoint = endpoint;
}
public String getAccessKeyId() {
return accessKeyId;
}
public void setAccessKeyId(String accessKeyId) {
this.accessKeyId = accessKeyId;
}
public String getAccessKeySecret() {
return accessKeySecret;
}
public void setAccessKeySecret(String accessKeySecret) {
this.accessKeySecret = accessKeySecret;
}
public String getBucketName() {
return bucketName;
}
public void setBucketName(String bucketName) {
this.bucketName = bucketName;
}
public String getUrlPrefix() {
return urlPrefix;
}
public void setUrlPrefix(String urlPrefix) {
this.urlPrefix = urlPrefix;
}
}
该类用于返回给前端的数据结构定义
public class PicUploadResult {
// 文件唯一标识
private String uid;
// 文件名
private String name;
// 状态有:uploading done error removed
private String status;
// 服务端响应内容,如:'{"status": "success"}'
private String response;
public String getUid() {
return uid;
}
public void setUid(String uid) {
this.uid = uid;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public String getResponse() {
return response;
}
public void setResponse(String response) {
this.response = response;
}
}
具体的上传逻辑实现,在该类中调用了OSS客户端的API。
@Service
public class picUploadService {
// 允许上传的格式
private static final String[] IMAGE_TYPE = new String[]{".bmp", ".jpg", ".jpeg", ".gif", ".png"};
@Autowired
private OSS ossClient;
@Autowired
private AlyunConfig aliyunConfig;
public PicUploadResult upload(MultipartFile uploadFile) {
// 校验图片格式
boolean isLegal = false;
for (String type : IMAGE_TYPE) {
if (StringUtils.endsWithIgnoreCase(uploadFile.getOriginalFilename(),
type)) {isLegal = true;
break;
}
} // 封装Result对象,并且将文件的byte数组放置到result对象中
PicUploadResult fileUploadResult = new PicUploadResult();
if(!isLegal){
fileUploadResult.setStatus("error");
return fileUploadResult;
} // 文件新路径
String fileName = uploadFile.getOriginalFilename();
String filePath = getFilePath(fileName);
// 上传到阿里云
try {
ossClient.putObject(aliyunConfig.getBucketName(), filePath, new ByteArrayInputStream(uploadFile.getBytes()));
} catch (Exception e) {
e.printStackTrace();
//上传失败
fileUploadResult.setStatus("error");
return fileUploadResult;
}
fileUploadResult.setStatus("done");
fileUploadResult.setName(this.aliyunConfig.getUrlPrefix() + filePath);
fileUploadResult.setUid(String.valueOf(System.currentTimeMillis()));
return fileUploadResult;
}
private String getFilePath(String sourceFileName) {
DateTime dateTime = new DateTime();
return "images/" + dateTime.toString("yyyy")
+ "/" + dateTime.toString("MM") + "/"
+ dateTime.toString("dd") + "/" + System.currentTimeMillis() +
RandomUtils.nextInt(100, 9999) + "." +
StringUtils.substringAfterLast(sourceFileName, ".");
}
}
这里生成图片id为了方便采用的是以当前秒数做id
@Controller
public class PicUploadController {
@Autowired
private picUploadService picUploadService;
@RequestMapping("/pic/upload")
@PostMapping
@ResponseBody
public PicUploadResult upload(@RequestParam("file") MultipartFile uploadFile)
throws Exception {
return this.picUploadService.upload(uploadFile);
}
}
启动启动类PicApplication
测试工具:Postman
注意这里的key一定要与@RequestParam("file") 中的相同
上传文件时报错:
显示文件的大小超出了允许的范围。查看了官方文档,原来Spring Boot工程嵌入的tomcat限制了请求的文件大小
我这里使用的是spring boot2.0
解决办法:
在yml文件配置
其它Spring boot版本配置可以参考这篇博客https://blog.csdn.net/u010429286/article/details/54381705
最后问题解决 数据正确返回
访问name地址查看图片 查看oss中是否有该文件
@Service
public class PicUploadFileSystemService {
// 允许上传的格式
private static final String[] IMAGE_TYPE = new String[]{".bmp", ".jpg",
".jpeg", ".gif", ".png"};
public PicUploadResult upload(MultipartFile uploadFile) {
//校验图片格式
boolean isLegal = false;
for (String type : IMAGE_TYPE) {
if (StringUtils.endsWithIgnoreCase(uploadFile.getOriginalFilename(),
type)) {
isLegal = true;
break;
}
}
// 封装Result对象,并且将文件的byte数组放置到result对象中
PicUploadResult fileUploadResult = new PicUploadResult();
if (!isLegal) {
fileUploadResult.setStatus("error");
return fileUploadResult;
}
// 文件新路径
String fileName = uploadFile.getOriginalFilename();
String filePath = getFilePath(fileName);
// 生成图片的绝对引用地址
String picUrl = StringUtils.replace(StringUtils.substringAfter(filePath,
"E:\\code\\test-upload\\images"),
"\\", "/");
//访问路径
fileUploadResult.setName("www.test.image" + picUrl);
File newFile = new File(filePath);
// 写文件到磁盘
try {
uploadFile.transferTo(newFile);
} catch (IOException e) {
e.printStackTrace();
//上传失败
fileUploadResult.setStatus("error");
return fileUploadResult;
}
fileUploadResult.setStatus("done");
fileUploadResult.setUid(String.valueOf(System.currentTimeMillis()));
return fileUploadResult;
}
private String getFilePath(String sourceFileName) {
String baseFolder = "E:\\code\\test-upload" + File.separator
+ "images";
Date nowDate = new Date();
// yyyy/MM/dd
String fileFolder = baseFolder + File.separator + new
DateTime(nowDate).toString("yyyy")
+ File.separator + new DateTime(nowDate).toString("MM") +
File.separator
+ new DateTime(nowDate).toString("dd");
File file = new File(fileFolder);
if (!file.isDirectory()) {
// 如果目录不存在,则创建目录
file.mkdirs();
}
// 生成新的文件名
String fileName = new DateTime(nowDate).toString("yyyyMMddhhmmssSSSS")
+ RandomUtils.nextInt(100, 9999) + "." +
StringUtils.substringAfterLast(sourceFileName, ".");
return fileFolder + File.separator + fileName;
}
}
@Controller
public class PicUploadController {
@Autowired
private PicUploadFileSystemService picUploadFileSystemService;
@RequestMapping("/pic/upload")
@PostMapping
@ResponseBody
public PicUploadResult upload(@RequestParam("file") MultipartFile uploadFile)
throws Exception {
return this.picUploadFileSystemService.upload(uploadFile);
}
}
修改nginx.conf文件
启动nginx
由于没有域名 这里测试就通过SwitchHosts软件修改本地host文件来实现域名访问
软件下载链接https://download.csdn.net/download/guisu97/11224672
访问