头像上传

This commit is contained in:
liang.chao 2024-01-23 16:09:25 +08:00
parent a008a459cd
commit 88e5c4a21c
3 changed files with 126 additions and 41 deletions

View File

@ -1,17 +1,20 @@
package com.bonus.sgzb.system.controller; package com.bonus.sgzb.system.controller;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.util.Arrays; import java.util.Arrays;
import org.springframework.beans.factory.annotation.Autowired; import cn.hutool.core.util.IdUtil;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import com.bonus.sgzb.common.core.domain.R; import com.bonus.sgzb.common.core.domain.R;
import com.bonus.sgzb.common.core.utils.DateTimeHelper;
import com.bonus.sgzb.system.api.domain.SysFile;
import com.bonus.sgzb.system.domain.FileInfo;
import com.bonus.sgzb.system.service.SysFileService;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import com.bonus.sgzb.common.core.utils.StringUtils; import com.bonus.sgzb.common.core.utils.StringUtils;
import com.bonus.sgzb.common.core.utils.file.FileTypeUtils; import com.bonus.sgzb.common.core.utils.file.FileTypeUtils;
import com.bonus.sgzb.common.core.utils.file.MimeTypeUtils; import com.bonus.sgzb.common.core.utils.file.MimeTypeUtils;
@ -22,10 +25,14 @@ import com.bonus.sgzb.common.log.enums.BusinessType;
import com.bonus.sgzb.common.security.service.TokenService; import com.bonus.sgzb.common.security.service.TokenService;
import com.bonus.sgzb.common.security.utils.SecurityUtils; import com.bonus.sgzb.common.security.utils.SecurityUtils;
import com.bonus.sgzb.system.api.RemoteFileService; import com.bonus.sgzb.system.api.RemoteFileService;
import com.bonus.sgzb.system.api.domain.SysFile;
import com.bonus.sgzb.system.api.domain.SysUser; import com.bonus.sgzb.system.api.domain.SysUser;
import com.bonus.sgzb.system.api.model.LoginUser; import com.bonus.sgzb.system.api.model.LoginUser;
import com.bonus.sgzb.system.service.ISysUserService; import com.bonus.sgzb.system.service.ISysUserService;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
/** /**
* 个人信息 业务处理 * 个人信息 业务处理
@ -44,6 +51,9 @@ public class SysProfileController extends BaseController {
@Autowired @Autowired
private RemoteFileService remoteFileService; private RemoteFileService remoteFileService;
@Resource
private SysFileService sysFileService;
/** /**
* 个人信息 * 个人信息
*/ */
@ -113,27 +123,27 @@ public class SysProfileController extends BaseController {
*/ */
@Log(title = "用户头像", businessType = BusinessType.UPDATE) @Log(title = "用户头像", businessType = BusinessType.UPDATE)
@PostMapping("/avatar") @PostMapping("/avatar")
public AjaxResult avatar(@RequestParam("avatarfile") MultipartFile file) { public AjaxResult avatar(@RequestParam("avatarfile") MultipartFile file,String fileType) throws Exception {
if (!file.isEmpty()) { FileInfo fileInfo = sysFileService.uploadHeadPic(file, fileType);
LoginUser loginUser = SecurityUtils.getLoginUser(); if (!file.isEmpty()) {
String extension = FileTypeUtils.getExtension(file); LoginUser loginUser = SecurityUtils.getLoginUser();
if (!StringUtils.equalsAnyIgnoreCase(extension, MimeTypeUtils.IMAGE_EXTENSION)) { String extension = FileTypeUtils.getExtension(file);
return error("文件格式不正确,请上传" + Arrays.toString(MimeTypeUtils.IMAGE_EXTENSION) + "格式"); if (!StringUtils.equalsAnyIgnoreCase(extension, MimeTypeUtils.IMAGE_EXTENSION)) {
return error("文件格式不正确,请上传" + Arrays.toString(MimeTypeUtils.IMAGE_EXTENSION) + "格式");
}
if (ObjectUtils.isEmpty(fileInfo)) {
return error("文件服务异常,请联系管理员");
}
String url = fileInfo.getFileUrl();
if (userService.updateUserAvatar(loginUser.getUsername(), url)) {
AjaxResult ajax = AjaxResult.success();
ajax.put("imgUrl", url);
// 更新缓存用户头像
loginUser.getSysUser().setAvatar(url);
tokenService.setLoginUser(loginUser);
return ajax;
}
} }
R<SysFile> fileResult = remoteFileService.upload(file);
if (StringUtils.isNull(fileResult) || StringUtils.isNull(fileResult.getData())) {
return error("文件服务异常,请联系管理员");
}
String url = fileResult.getData().getUrl();
if (userService.updateUserAvatar(loginUser.getUsername(), url)) {
AjaxResult ajax = AjaxResult.success();
ajax.put("imgUrl", url);
// 更新缓存用户头像
loginUser.getSysUser().setAvatar(url);
tokenService.setLoginUser(loginUser);
return ajax;
}
}
return error("上传图片异常,请联系管理员"); return error("上传图片异常,请联系管理员");
} }
} }

View File

@ -2,6 +2,7 @@ package com.bonus.sgzb.system.service;
import com.bonus.sgzb.system.domain.FileInfo; import com.bonus.sgzb.system.domain.FileInfo;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletRequest;
@ -20,4 +21,6 @@ public interface SysFileService
*/ */
FileInfo uploadFile(HttpServletRequest request) throws Exception; FileInfo uploadFile(HttpServletRequest request) throws Exception;
FileInfo uploadHeadPic(MultipartFile file,String fileType) throws Exception;
} }

View File

@ -55,11 +55,11 @@ public class SysFileServiceImpl implements SysFileService {
MultipartFile item = items.get(0); MultipartFile item = items.get(0);
try { try {
String url = saveFile(request, item, photoType); String url = saveFile(request, item, photoType);
if(url != null){ if (url != null) {
int words = getFileText(item); int words = getFileText(item);
String fileName = item.getOriginalFilename(); String fileName = item.getOriginalFilename();
String type = fileName.substring(fileName.lastIndexOf(".") + 1); String type = fileName.substring(fileName.lastIndexOf(".") + 1);
long size = item.getSize()/1024/1024; long size = item.getSize() / 1024 / 1024;
file.setFileName(fileName); file.setFileName(fileName);
file.setFileUrl(url); file.setFileUrl(url);
file.setCreator(userId.toString()); file.setCreator(userId.toString());
@ -76,6 +76,40 @@ public class SysFileServiceImpl implements SysFileService {
return file; return file;
} }
/**
* 头像上传
*
* @return 访问地址
* @throws Exception
*/
@Override
public FileInfo uploadHeadPic(MultipartFile item,String fileType) {
FileInfo file = new FileInfo();
Long userId = SecurityUtils.getUserId();
try {
String url = saveFilePic(item, fileType);
if (url != null) {
int words = getFileText(item);
String fileName = item.getOriginalFilename();
String type = fileName.substring(fileName.lastIndexOf(".") + 1);
long size = item.getSize() / 1024 / 1024;
file.setFileName(fileName);
file.setFileUrl(url);
file.setCreator(userId.toString());
file.setType(type);
file.setSize(size + "M");
file.setWords(words);
file.setCreateBy(SecurityUtils.getUserId().toString());
file.setCreateTime(new Date());
dao.insertFileInfo(file);
}
} catch (Exception e) {
e.printStackTrace();
}
return file;
}
public HashMap<String, Object> getFile(StandardMultipartHttpServletRequest request) { public HashMap<String, Object> getFile(StandardMultipartHttpServletRequest request) {
MultipartFile multipartFile; MultipartFile multipartFile;
HashMap<String, Object> map = new HashMap<String, Object>(); HashMap<String, Object> map = new HashMap<String, Object>();
@ -86,7 +120,7 @@ public class SysFileServiceImpl implements SysFileService {
multipartFile = request.getFile(itr.next()); multipartFile = request.getFile(itr.next());
tmps.add(multipartFile); tmps.add(multipartFile);
} }
map.put("filePath",tmps); map.put("filePath", tmps);
} catch (Exception e) { } catch (Exception e) {
e.printStackTrace(); e.printStackTrace();
} }
@ -97,22 +131,60 @@ public class SysFileServiceImpl implements SysFileService {
String url = ""; String url = "";
String tmpName = multipartFile.getOriginalFilename();// 完整路径 IE String tmpName = multipartFile.getOriginalFilename();// 完整路径 IE
tmpName = tmpName.substring(tmpName.lastIndexOf("\\") + 1); tmpName = tmpName.substring(tmpName.lastIndexOf("\\") + 1);
tmpName = IdUtil.fastSimpleUUID() + System.currentTimeMillis() +tmpName.substring(tmpName.lastIndexOf("."),tmpName.length()); tmpName = IdUtil.fastSimpleUUID() + System.currentTimeMillis() + tmpName.substring(tmpName.lastIndexOf("."), tmpName.length());
String imageFiles="/data/sgzb/" + fileType + "/"; String imageFiles = "/data/sgzb/" + fileType + "/";
String os = System.getProperty("os.name"); String os = System.getProperty("os.name");
if(os.toLowerCase().startsWith("win")){ if (os.toLowerCase().startsWith("win")) {
imageFiles="D://files/" + fileType + "/"; imageFiles = "D://files/" + fileType + "/";
} }
String year = DateTimeHelper.getNowYear(); String year = DateTimeHelper.getNowYear();
String month = DateTimeHelper.getNowMonths(); String month = DateTimeHelper.getNowMonths();
String day = DateTimeHelper.getNowDay(); String day = DateTimeHelper.getNowDay();
String specfile = imageFiles + year +"/" + month +"/"+ day; String specfile = imageFiles + year + "/" + month + "/" + day;
File file = new File(specfile + "/" + tmpName); File file = new File(specfile + "/" + tmpName);
if (!file.getParentFile().exists()) { if (!file.getParentFile().exists()) {
file.getParentFile().mkdirs(); file.getParentFile().mkdirs();
} }
url = "/" + fileType + "/" + year +"/" + month +"/"+ day + "/" + tmpName; url = "/" + fileType + "/" + year + "/" + month + "/" + day + "/" + tmpName;
if (!multipartFile.isEmpty()) {
try {
FileOutputStream fos = new FileOutputStream(file);
InputStream in = multipartFile.getInputStream();
byte[] bytes = new byte[1024];
int len = 0;
while ((len = in.read(bytes)) != -1) {
fos.write(bytes, 0, len);
}
fos.close();
in.close();
} catch (Exception e) {
e.printStackTrace();
}
}
return url;
}
public String saveFilePic(MultipartFile multipartFile, String fileType) throws Exception {
String url = "";
String tmpName = multipartFile.getOriginalFilename();// 完整路径 IE
tmpName = tmpName.substring(tmpName.lastIndexOf("\\") + 1);
tmpName = IdUtil.fastSimpleUUID() + System.currentTimeMillis() + tmpName.substring(tmpName.lastIndexOf("."), tmpName.length());
String imageFiles = "/data/sgzb/" + fileType + "/";
String os = System.getProperty("os.name");
if (os.toLowerCase().startsWith("win")) {
imageFiles = "D://files/" + fileType + "/";
}
String year = DateTimeHelper.getNowYear();
String month = DateTimeHelper.getNowMonths();
String day = DateTimeHelper.getNowDay();
String specfile = imageFiles + year + "/" + month + "/" + day;
File file = new File(specfile + "/" + tmpName);
if (!file.getParentFile().exists()) {
file.getParentFile().mkdirs();
}
url = "/" + fileType + "/" + year + "/" + month + "/" + day + "/" + tmpName;
if (!multipartFile.isEmpty()) { if (!multipartFile.isEmpty()) {
try { try {
FileOutputStream fos = new FileOutputStream(file); FileOutputStream fos = new FileOutputStream(file);