在进行网页设计的时候遇到一些图片上传的问题
(1) 图片存哪
(2) 图片大小以及数量
考虑到如果不想使用文件io 读写,可以使用阿里云的OSS进行图片上传保存
1.登陆阿里云oss(本人使用阿里云)
进行开通oss操作,不仔细讲官网有教学。
并且获取必要参数写入 spring boot 配置文件
1 2 3 4 5 6
| # 阿里云OSS配置 aliyun.ak= **** aliyun.sk= **** aliyun.endpoint= **** aliyun.img.host= **** aliyun.bucketName= ****
|
2.spring boot 配置
2.1 pom.xml
1 2 3 4 5 6 7 8 9 10 11
| <dependency> <groupId>com.aliyun.oss</groupId> <artifactId>aliyun-sdk-oss</artifactId> <version>2.4.0</version> </dependency> <dependency> <groupId>commons-fileupload</groupId> <artifactId>commons-fileupload</artifactId> <version>1.3.1</version> </dependency>
|
2.2 文件上传class类
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52
| package com.dnake.sol.common;
import com.aliyun.oss.OSSClient; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Component; import org.springframework.web.multipart.MultipartFile;
import java.io.IOException; import java.io.InputStream; import java.util.UUID;
@Component public class FileUploadService {
@Value("${aliyun.endpoint}") private String endpoint;
@Value("${aliyun.ak}") private String accessKeyId;
@Value("${aliyun.sk}") private String accessKeySecret;
@Value("${aliyun.img.host}") private String imgHost;
public String upload(MultipartFile imgFile) throws IOException {
OSSClient ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret);
String fileName = imgFile.getOriginalFilename();
String uuid = UUID.randomUUID().toString().replace("-", "").toUpperCase(); String suffix = fileName.substring(fileName.lastIndexOf(".")); String uploadFileName = uuid + suffix;
InputStream inputStream = imgFile.getInputStream(); ossClient.putObject("skill-change", uploadFileName, inputStream); ossClient.shutdown();
return imgHost + uploadFileName; } }
|
剩下的就是 前后端交互
前端进行文件传入,后台进行MultipartFile 进行写入
1 2 3 4 5 6 7 8 9 10 11 12
| public BrewingJSONResult updaeUserImgByOpenid(String openid, MultipartFile imgFile) { String imgUrl; try { if (imgFile != null) { imgUrl = fileUploadService.upload(imgFile); return tpUserService.updateImgByOpenId(openid, imgUrl); } } catch (IOException e) { e.printStackTrace(); } return BrewingJSONResult.errorMsg("报错"); }
|
这时候文件就正常上传到阿里云上