SpringBoot头像上传
- 需求
- 七牛云网站上传头像
- FastDFS上传头像(暂存)
- 阿里云OSS(暂存)
需求
在个人中心点击编辑的时候可以上传头像图片。上传完头像后,可以用于更新个人信息接口。
把图片视频等文件上传到自己的应用的Web服务器,在读取图片的时候会占用比较多的资源,影响应用服务器的性能。
一般使用OSS(Object Storage Service对象存储服务)存储图片或视频。
七牛云网站上传头像
七牛云注册官网地址七牛云新建存储空间操作文档java使用参考官方文档 1.添加依赖
<dependency>
<groupId>com.qiniu</groupId>
<artifactId>qiniu-java-sdk</artifactId>
<version>[7.7.0, 7.7.99]</version>
</dependency>
2.application.yml配置密钥和存储空间名及外链url
oss:
accessKey: xxxx
secretKey: xxxx
bucket: fileName(存储空间名)
fileUrl: http://xxx.xx.com/
3.接口设计
UploadController方法
img,值为要上传的文件
请求头:Content-Type :multipart/form-data;
@RestController
public class UploadController {
@Autowired
private UploadService uploadService;
@PostMapping("/upload")
public ResponseResult uploadImg(MultipartFile img){
return uploadService.uploadImg(img);
}
}
application.yml 设置文件大小
spring:
servlet:
multipart:
max-file-size: 2MB
max-request-size: 5MB
service实现方法
@Service
@Slf4j
public class UploadServiceImpl implements UploadService {
//AK
@Value("${oss.accessKey}")
String accessKey;
//SK
@Value("${oss.secretKey}")
String secretKey;
//存储空间名
@Value("${oss.bucket}")
String bucket;
@Value("${oss.fileUrl}")
String fileUrl;
/**
*上传图片方法
*/
@Override
public ResponseResult uploadImg(MultipartFile file) {
//判断文件类型
//获取原始文件名
String originalFilename = file.getOriginalFilename();
//对原始文件名进行判断,是否是图片
if(!originalFilename.endsWith(".png")&&!originalFilename.endsWith(".jpg")){
throw new SystemException(AppHttpCodeEnum.FILE_TYPE_ERROR);
}
String filePath = PathUtils.generateFilePath(originalFilename);
//如果判断通过上传文件到oss
return ResponseResult.okResult(uploadOss(file, filePath));
}
private String uploadOss(MultipartFile imgFile,String filePath) {
Configuration cfg = new Configuration(Region.autoRegion());
UploadManager uploadManager = new UploadManager(cfg);
String key = filePath;
try {
//前端上传文件转为inputStream
InputStream inputStream = imgFile.getInputStream();
Auth auth = Auth.create(accessKey, secretKey);
String upToken = auth.uploadToken(bucket);
try {
Response response = uploadManager.put(inputStream, key, upToken, null, null);
//解析上传成功的结果
DefaultPutRet putRet = new Gson().fromJson(response.bodyString(), DefaultPutRet.class);
return fileUrl+key;
} catch (QiniuException ex) {
Response r = ex.response;
System.err.println(r.toString());
try {
System.err.println(r.bodyString());
} catch (QiniuException ex2) {
//ignore
}
}
} catch (Exception ex) {
//ignore
}
return "aaa";
}
}
PathUtils根据日期生成路径 2022/1/15
public class PathUtils {
public static String generateFilePath(String fileName){
//根据日期生成路径 2022/1/15/
SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd/");
String datePath = sdf.format(new Date());
//uuid作为文件名
String uuid = UUID.randomUUID().toString().replaceAll("-", "");
//后缀和文件后缀一致
int index = fileName.lastIndexOf(".");
// test.jpg -> .jpg
String fileType = fileName.substring(index);
return new StringBuilder().append(datePath).append(uuid).append(fileType).toString();
}
}
FastDFS上传头像(暂存)
安装参考:
1.引入依赖
<!--上传文件-->
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.3.1</version>
</dependency>
2.配置文件 src/main/resources/config/fastdfs-client.properties
##fastdfs-client.properties
fastdfs.connect_timeout_in_seconds = 5
fastdfs.network_timeout_in_seconds = 30
fastdfs.charset = UTF-8
fastdfs.http_anti_steal_token = false
fastdfs.http_secret_key = FastDFS1234567890
fastdfs.http_tracker_http_port = 80
fastdfs.tracker_servers = 192.168.204.141:22122
3.上传头像代码
@RestController
@RequestMapping("userSetting")
@CrossOrigin //跨域
public class UserController {
@Autowired
private UserService userService;
static String fastdfsip = null;
static{
Properties props = new Properties();
InputStream in = IniFileReader.loadFromOsFileSystemOrClasspathAsStream("config/fastdfs-client.properties");
if (in != null) {
try {
props.load(in);
} catch (IOException e) {
e.printStackTrace();
}
}
fastdfsip = props.getProperty("fastdfs.tracker_servers").split(":")[0];
}
@PostMapping("upload")
@ResponseBody
public FileSystem upload(@RequestParam("file") MultipartFile file) throws IOException {
System.out.println("接收到:" +file);
FileSystem fs = new FileSystem();
//获得文件的原始名称
String oldFileName = file.getOriginalFilename();
//获得后缀名
String hou = oldFileName.substring(oldFileName.lastIndexOf(".")+1);
try {
//加载配置文件
ClientGlobal.initByProperties("config/fastdfs-client.properties");
System.out.println("ip:" + fastdfsip );
//创建tracker客户端
TrackerClient tc = new TrackerClient();
//根据tracker客户端创建连接
TrackerServer ts = tc.getConnection();
StorageServer ss = null;
//定义storage客户端
StorageClient1 client = new StorageClient1(ts, ss);
//文件元信息
NameValuePair[] list = new NameValuePair[1];
list[0] = new NameValuePair("fileName", oldFileName);
//上传,返回fileId
String fileId = client.upload_file1(file.getBytes(), hou, list);
System.out.println(fileId);
ts.close();
//封装数据对象,将路径保存到数据库(本次不写)
fs.setFileId(fileId);
fs.setFilePath(fileId);
fs.setFileName(oldFileName);
} catch (Exception e) {
e.printStackTrace();
}
return fs;
}
上传文件的实体类
@Data
@AllArgsConstructor
@NoArgsConstructor
@ToString
public class FileSystem {
private String fileId;
private String filePath;
private String fileName;
阿里云OSS(暂存)
阿里云oss是一个很好的分布式文件服务系统,所以我们只需要集成阿里云oss即可。
1.引入依赖
<!-- 阿里云oss依赖 -->
<dependency>
<groupId>com.aliyun.oss</groupId>
<artifactId>aliyun-sdk-oss</artifactId>
</dependency>
<!-- 日期工具栏依赖 -->
<dependency>
<groupId>joda-time</groupId>
<artifactId>joda-time</artifactId>
</dependency>
2.配置文件
aliyun:
oss:
endpoint: oss-cn-beijing.aliyuncs.com
accessKeyId: LTAI4G4SV6WtST7UYH776xxx
secret: X9KHNYgztNr9MI5Zp8JffQPZO4uxxx
bucket: xxx
controller:
@RestController
@RequestMapping("file")
public class FileController {
@Autowired
private FileService fileService;
//上传文件到阿里云oss
@PostMapping("fileUpload")
public String fileUpload(@RequestParam("file") MultipartFile file) {
//获取上传文件
String url = fileService.upload(file);
return url;
}
}
service:
@Service
public class FileServiceImpl implements FileService {
@Value("${aliyun.oss.endpoint}")
private String endpoint;
@Value("${aliyun.oss.accessKeyId}")
private String accessKeyId;
@Value("${aliyun.oss.secret}")
private String secret;
@Value("${aliyun.oss.bucket}")
private String bucket;
@Override
public String upload(MultipartFile file) {
try {
// 创建OSSClient实例。
OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
// 上传文件流。
InputStream inputStream = file.getInputStream();
String fileName = file.getOriginalFilename();
// 生成随机唯一值,使用uuid,添加到文件名称里面
String uuid = UUID.randomUUID().toString().replaceAll("-","");
fileName = uuid+fileName;
//按照当前日期,创建文件夹,上传到创建文件夹里面
// 2021/02/02/01.mp4
String timeUrl = new DateTime().toString("yyyy/MM/dd");
fileName = timeUrl+"/"+fileName; // 2021/02/02/23fads85rj4hka01.mp4
// 调用方法实现上传
ossClient.putObject(bucketName, fileName, inputStream);
// 关闭OSSClient。
ossClient.shutdown();
// 上传之后文件路径
// https://lagou-laosun.oss-cn-beijing.aliyuncs.com/01.jpg
String url = "https://"+bucketName+"."+endpoint+"/"+fileName;
// 返回
return url;
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
}