1、导入依赖 - pom.xml
<dependency>
<groupId>com.aliyun.oss</groupId>
<artifactId>aliyun-sdk-oss</artifactId>
<version>3.11.1</version>
</dependency>
<dependency>
<groupId>joda-time</groupId>
<artifactId>joda-time</artifactId>
<version>2.10.8</version>
</dependency>
2、写配置 - application.properties
#阿里云 OSS
aliyun.oss.file.endpoint=你的 oss-cn-shenzhen.aliyuncs.com
aliyun.oss.file.keyid=你的 access-key
aliyun.oss.file.keysecret=你的 secret-key:
aliyun.oss.file.bucketname=你的桶名
3、配置常量工具类 - OssConstantUtils
package com.jili20.util;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
@Component
public class OssConstantUtils implements InitializingBean {
@Value("${aliyun.oss.file.endpoint}")
private String endpoint;
@Value("${aliyun.oss.file.keyid}")
private String keyId;
@Value("${aliyun.oss.file.keysecret}")
private String keySecret;
@Value("${aliyun.oss.file.bucketname}")
private String bucketName;
public static String END_POIND;
public static String ACCESS_KEY_ID;
public static String ACCESS_KEY_SECRET;
public static String BUCKET_NAME;
@Override
public void afterPropertiesSet() throws Exception {
END_POIND = endpoint;
ACCESS_KEY_ID = keyId;
ACCESS_KEY_SECRET = keySecret;
BUCKET_NAME = bucketName;
}
}
4、上传头像控制器- UserController
package com.jili20.controller;
。。。。。。
@Controller
public class UserController implements CommunityConstant {
private static final Logger logger = (Logger) LoggerFactory.getLogger(UserController.class);
@Autowired
private UserService userService;
@Autowired
private HostHolder hostHolder;
@LoginRequired
@GetMapping("/user/setting")
public String getSettingPage() {
return "/site/setting";
}
@LoginRequired
@PostMapping("/user/upload")
public String uploadHeader(MultipartFile headerImage, Model model, RedirectAttributes attr) {
if (headerImage == null) {
model.addAttribute("error", "您还没有选择图片!");
return "/site/setting";
}
String endpoint = OssConstantUtils.END_POIND;
String accessKeyId = OssConstantUtils.ACCESS_KEY_ID;
String accessKeySecret = OssConstantUtils.ACCESS_KEY_SECRET;
String bucketName = OssConstantUtils.BUCKET_NAME;
try {
OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
InputStream inputStream = headerImage.getInputStream();
String fileName = headerImage.getOriginalFilename();
String uuid = UUID.randomUUID().toString().replaceAll("-", "");
fileName = uuid + fileName;
String datePath = new DateTime().toString("yyyy/MM/dd");
fileName = datePath + "/" + fileName;
ossClient.putObject(bucketName, fileName, inputStream);
ossClient.shutdown();
User user = hostHolder.getUser();
String headerUrl = "https://" + bucketName + "." + endpoint + "/" + fileName;
int rows = userService.updateHeader(user.getId(), headerUrl);
if (rows > 0) {
attr.addFlashAttribute("uploadMsg", "上传头像成功");
}
return "redirect:/user/setting";
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
}
5、用户设置页面上传头像表单 - templates/site/setting.html
<form class="mt-5" method="post" enctype="multipart/form-data" th:action="@{/user/upload}">
<div class="form-group row mt-4">
<label for="head-image" class="col-sm-2 col-form-label text-right">选择头像:</label>
<div class="col-sm-10">
<div class="custom-file">
<input type="file" th:class="|custom-file-input ${error!=null?'is-invalid':''}|"
id="head-image" name="headerImage" lang="es" required="">
<label class="custom-file-label" for="head-image" data-browse="文件">选择一张图片</label>
<div class="invalid-feedback" th:text="${error}">
该账号不存在!
</div>
</div>
</div>
</div>
<div class="form-group row mt-4">
<div class="col-sm-2"></div>
<div class="col-sm-10 text-center">
<button type="submit" class="btn btn-info text-white form-control">立即上传</button>
</div>
</div>
</form>
完