因项目中需要在添加用户、修改用户时上传用户头像,并显示出来。
详细代码如下:
一、controller层
/**
* @Author: liumce
* @Description: 头像上传功能控制
* @Date: Created in 2021/09/14 17:03
* @Modified By:
*/
@Controller
@RequestMapping("/upload")
public class UploadController {
private Logger logger = LoggerFactory.getLogger(this.getClass());
@Autowired
private UserMapper userMapper;
@ResponseBody
@PostMapping(value = "/image")
public JsonResult imgUpload(@RequestParam(value = "file") MultipartFile file,String userNumber) {
if (null==userMapper.queryByUserNumber(userNumber)) {
throw new ImcsUserCenterException("该用户不存在!");
}
if (file.isEmpty()) {
throw new ImcsUserCenterException("头像文件不能为空!");
}
String fileName = file.getOriginalFilename();
String suffixName = fileName.substring(fileName.lastIndexOf("."));
String folder = "/" + LocalDateTimeUtils.formatNow("yyyyMMdd") + "/";
fileName = System.currentTimeMillis() + suffixName;
File dest = ImgUtil.createFile(PathsUtils.getAbsolutePath(ConfigConstValue.rootPath + folder + fileName));
try {
file.transferTo(dest);
// 上面是保存图片,先让它保存成功然后再修改数据库
String fileUrl = folder + fileName;
Map<String,Object> paramMap = new HashMap<>();
paramMap.put("fileUrl",fileUrl);
paramMap.put("userNumber",userNumber);
userMapper.insertImg(paramMap);
} catch (IOException e) {
logger.error(e.getMessage(), e);
ErrUtils.err(ApiResultEnum.FILE_UPLOAD_ERR);
}
return JsonResultBuilder.successMessage(ConfigConstValue.prePath + folder + fileName);
}
}
/**
* @Author: liumce
* @Description:
* @Date: Created in 2021/09/14 20:03
* @Modified By:
*/
@Slf4j
@Controller
@RequestMapping("/show")
public class ShowImagesController {
//显示本地图片
@GetMapping(value = "/{filename:.+}")
public void getImg(@PathVariable("filename") String filename, HttpServletRequest request, HttpServletResponse response) throws IOException {
String address = ConfigConstValue.rootPath +"/"+filename;
writeImg(response, PathsUtils.getAbsolutePath(address));
}
@GetMapping(value = "/{folderName}/{filename:.+}")
public void getImg(@PathVariable("folderName") String folderName, @PathVariable("filename") String filename, HttpServletRequest request, HttpServletResponse response) throws IOException {
String address = ConfigConstValue.rootPath+"/"+folderName+"/"+filename;
writeImg(response,PathsUtils.getAbsolutePath(address));
}
@GetMapping(value = "/{folderName}/{folderName2}/{filename:.+}")
public void getImg(@PathVariable("folderName") String folderName, @PathVariable("folderName2") String folderName2, @PathVariable("filename") String filename, HttpServletRequest request, HttpServletResponse response) throws IOException {
String address = ConfigConstValue.rootPath+"/"+folderName+"/"+folderName2+"/"+filename;
writeImg(response, PathsUtils.getAbsolutePath(address));
}
//获取图片的绝对地址
public FileInputStream query_getPhotoImageBlob(String adress) {
FileInputStream is = null;
File filePic = new File(adress);
try {
is = new FileInputStream(filePic);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
return is;
}
//输出图片
public void writeImg(HttpServletResponse response, String address) throws IOException {
response.setContentType("image/jpeg");
FileInputStream is =this.query_getPhotoImageBlob(address);
if (is != null){
int i = is.available(); // 得到文件大小
byte data[] = new byte[i];
is.read(data); // 读数据
is.close();
response.setContentType("image/jpeg"); // 设置返回的文件类型
OutputStream toClient = response.getOutputStream(); // 得到向客户端输出二进制数据的对象
toClient.write(data); // 输出数据
toClient.close();
}
}
二、mapper
void insertImg(Map conditions);
三、util
public class ImgUtil {
/**
* 上传文件
* @param filePath 文件名
* @param in io流
* @return 返回最终的路径
* @throws IOException
*/
public static String uploadImg(String rootPATH, String filePath, InputStream in) throws IOException {
System.out.println("rootPATH="+rootPATH);
System.out.println("filePath="+filePath);
String rusultPath = rootPATH+filePath;
createFile(rusultPath);
File realFile =new File(rusultPath);
FileUtils.copyInputStreamToFile(in, realFile);
return "/upload/show"+filePath;
}
/**
* 上传图片
* @param filePath 图片路径
* @param in io流
* @throws IOException
*/
public static void uploadImg(String filePath,InputStream in) throws IOException{
createFile(filePath);
File realFile =new File(filePath);
FileUtils.copyInputStreamToFile(in, realFile);
}
/**
* 文件或文件夹不存在则创建
* @param dir 文件夹
* @param filepath 文件名
*/
public static void createFile(String dir,String filepath){
File file = new File(dir);
if(!file.exists()){
file.mkdirs();
}
file = new File(dir+filepath);
if(!file.exists()){
try {
file.createNewFile();
} catch (IOException e) {
System.out.println("文件创建失败");
e.printStackTrace();
}
}
}
/**
* 保存图片通过url
*
* @param urlString
* @param filename
* @throws Exception
*/
public static void saveImgByUrl(String urlString, String filename) throws Exception {
System.out.println("filename="+filename);
System.out.println("urlString="+urlString);
createFile(filename);
// 构造URL
URL url = new URL(urlString);
// 打开连接
URLConnection con = url.openConnection();
// 输入流
InputStream is = con.getInputStream();
// 1K的数据缓冲
byte[] bs = new byte[2048];
// 读取到的数据长度
int len;
// 输出的文件流
OutputStream os = new FileOutputStream(filename);
// 开始读取
while ((len = is.read(bs)) != -1) {
os.write(bs, 0, len);
}
// 完毕,关闭所有链接
os.close();
is.close();
}
/**
* 创建文件,如果文件夹不存在将被创建
*
* @param destFileName
* 文件路径
*/
public static File createFile(String destFileName) {
File file = new File(destFileName);
if (file.exists())
return null;
if (destFileName.endsWith(File.separator))
return null;
if (!file.getParentFile().exists()) {
if (!file.getParentFile().mkdirs())
return null;
}
try {
if (file.createNewFile())
return file;
return null;
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
}
public class LocalDateTimeUtils {
//获取当前时间的LocalDateTime对象
//LocalDateTime.now();
//根据年月日构建LocalDateTime
//LocalDateTime.of();
//比较日期先后
//LocalDateTime.now().isBefore(),
//LocalDateTime.now().isAfter(),
/**
* Date转换为LocalDateTime
*/
public static LocalDateTime convertDateToLDT(Date date) {
return LocalDateTime.ofInstant(date.toInstant(), ZoneId.systemDefault());
}
/**
* LocalDateTime转换为Date
*/
public static Date convertLDTToDate(LocalDateTime time) {
return Date.from(time.atZone(ZoneId.systemDefault()).toInstant());
}
/**
* 获取指定日期的毫秒
*/
public static Long getMilliByTime(LocalDateTime time) {
return time.atZone(ZoneId.systemDefault()).toInstant().toEpochMilli();
}
/**
* 获取指定日期的秒
*/
public static Long getSecondsByTime(LocalDateTime time) {
return time.atZone(ZoneId.systemDefault()).toInstant().getEpochSecond();
}
/**
* 获取指定时间的指定格式
*/
public static String formatTime(LocalDateTime time,String pattern) {
return time.format(DateTimeFormatter.ofPattern(pattern));
}
/**
* 获取当前时间的指定格式
*/
public static String formatNow(String pattern) {
return formatTime(LocalDateTime.now(), pattern);
}
/**
* 格式化
* @return
*/
public static String formatDateTimeNow() {
return formatNow("yyyy-MM-dd HH:mm:ss");
}
/**
* 格式化
* @return
*/
public static String formatDateNow() {
return formatNow("yyyy-MM-dd");
}
/**
* 日期加上一个数,根据field不同加不同值,field为ChronoUnit.*
*/
public static LocalDateTime plus(LocalDateTime time, long number, TemporalUnit field) {
return time.plus(number, field);
}
/**
* 日期减去一个数,根据field不同减不同值,field参数为ChronoUnit.*
*/
public static LocalDateTime minu(LocalDateTime time, long number, TemporalUnit field){
return time.minus(number,field);
}
/**
* 获取两个日期的差 field参数为ChronoUnit.*
* @param startTime
* @param endTime
* @param field 单位(年月日时分秒)
* @return
*/
public static long betweenTwoTime(LocalDateTime startTime, LocalDateTime endTime, ChronoUnit field) {
Period period = Period.between(LocalDate.from(startTime), LocalDate.from(endTime));
if (field == ChronoUnit.YEARS) {
return period.getYears();
}
if (field == ChronoUnit.MONTHS) {
return period.getYears() * 12 + period.getMonths();
}
return field.between(startTime, endTime);
}
/**
* 获取一天的开始时间,2017,7,22 00:00
*/
public static LocalDateTime getDayStart(LocalDateTime time) {
return time.withHour(0)
.withMinute(0)
.withSecond(0)
.withNano(0);
}
/**
* 获取一天的结束时间,2017,7,22 23:59:59.999999999
*/
public static LocalDateTime getDayEnd(LocalDateTime time) {
return time.withHour(23)
.withMinute(59)
.withSecond(59)
.withNano(999999999);
}
public class PathsUtils {
public static String getAbsolutePath(String path){
return System.getProperty("user.dir")+"/"+path;
}
private static String splitString(String str, String param) {
String result = str;
if (str.contains(param)) {
int start = str.indexOf(param);
result = str.substring(0, start);
}
return result;
}
/*
* 获取classpath1
*/
public static String getClasspath(){
String path = (String.valueOf(Thread.currentThread().getContextClassLoader().getResource(""))+"../../").replaceAll("file:/", "").replaceAll("%20", " ").trim();
if(path.indexOf(":") != 1){
path = File.separator + path;
}
return path;
}
/*
* 获取classpath2
*/
public static String getClassResources(){
String path = (String.valueOf(Thread.currentThread().getContextClassLoader().getResource(""))).replaceAll("file:/", "").replaceAll("%20", " ").trim();
if(path.indexOf(":") != 1){
path = File.separator + path;
}
return path;
}
四、exception
public class ErrUtils {
public static void err(ApiResultEnum resultCode){
throw new DeerException(resultCode);
}
public static void err(ApiResultEnum apiResultEnum, String... params){
throw new DeerException(apiResultEnum,params);
}
}
public enum ApiResultEnum {
SUCCESS("200","ok"),
FAILED("400","请求失败"),
ERROR("500","服务繁忙"),
TOKEN_USER_INVALID("10000","Token过期或无效"),
TOKEN_IS_NULL("10001","Token不能为空"),
ACCESS_DENIED("10002","无权访问"),
NEED_LOGIN("10002","需要登陆"),
LOGOUT_SUCCESS("10002","注销成功"),
USER_EXIST("20000","用户名已存在"),
EMAIL_EXIST("20001","邮箱已存在"),
EMAIL_ERROR("20002","邮箱格式错误"),
SEND_EMAIL_ERROR("20003","邮件发送失败,请稍后重试"),
CODE_VALID("20004","验证码已过期"),
CODE_ERROR("20005","验证码不匹配"),
UUID_ERROR("20006","UUID不能为空"),
CODE_NULL_ERROR("20007","验证码不能为空"),
NICKNAME_EXIST("20008","昵称已被使用"),
REQUEST_LIMIT("30000","请求重复提交"),
FILE_NULL("40000","文件不能为空"),
FILE_UPLOAD_ERR("40001","上次文件失败"),
;
private String message;
private String status;
public String getMessage() {
return message;
}
public String getStatus() {
return status;
}
private ApiResultEnum(String status, String message) {
this.message = message;
this.status = status;
}
}
/**
* 自定义异常
*/
@Data
@Accessors(chain = true)
public class DeerException extends RuntimeException{
private String status;
private String message;
private Object data;
private Exception exception;
private Object[] parameters;
public DeerException() {
super();
}
public DeerException(String status, String message, Object data, Object[] parameters, Exception exception) {
this.status = status;
this.parameters=parameters;
for (int i = 0; this.parameters != null && i < this.parameters.length; i++) {
message = message.replace("{" + i +"}", this.parameters[i].toString());
}
this.message = message;
this.data = data;
this.exception = exception;
}
public DeerException(ApiResultEnum apiResultEnum) {
this(apiResultEnum.getStatus(),apiResultEnum.getMessage(),null,null,null);
}
public DeerException(ApiResultEnum apiResultEnum, Object... parameters) {
this(apiResultEnum.getStatus(),apiResultEnum.getMessage(),null,parameters,null);
}
public DeerException(ApiResultEnum apiResultEnum, Object data, Exception exception) {
this(apiResultEnum.getStatus(),apiResultEnum.getMessage(),data,null,exception);
}
}
五、mybatis
<update id="insertImg" parameterType="java.util.Map">
update user
set profile_image = #{fileUrl}
where user_number = #{userNumber}
</update>
版权声明:本文为sinat_38239454原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。