图片上传

mac2023-06-10  34

package com.mima.online.util;

import com.mima.online.pojo.nurse.Nurse; import lombok.extern.slf4j.Slf4j; import org.apache.commons.lang3.StringUtils; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Component; import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO; import javax.servlet.http.HttpSession; import java.awt.image.BufferedImage; import java.io.File; import java.io.IOException; import java.util.HashMap; import java.util.Map; import java.util.Objects;

/** 文件工具类

@author EDZ */ @Slf4j @Component public class FileUploadUtil {

@Value("${fileUpload.imageTempPath}") private String tempPath;

@Value("${fileUpload.imagePath}") private String realPath;

/*可上传的图片类型/ private static final String[] IMAGE_TYPE = new String[] {".jpg",".jpeg",".png",".gif",".bmp"};

/**

图片上传@param multipartFile@return */ public JsonResult imageUpload(HttpSession session,MultipartFile multipartFile){ Map<String,Object> resultMap = new HashMap<>(1); if(multipartFile == null) { return new JsonResult(ResultCode.PARAMS_ERROR,“文件不存在!”); } //校验图片 boolean isLegal = false; //1,校验图片的后缀 //获取原来的文件名 String oldName = multipartFile.getOriginalFilename(); //获取文件后缀 for (String suffix : IMAGE_TYPE) { if(StringUtils.endsWithIgnoreCase(oldName, suffix)) { isLegal = true; break; } } if(!isLegal) { return new JsonResult(ResultCode.EXCEPTION,“文件类型不合法!”); } //2,校验是否为图片 try { BufferedImage bufferedImage = ImageIO.read(multipartFile.getInputStream()); } catch (IOException e) { return new JsonResult(ResultCode.EXCEPTION,“文件内容不匹配!”); } //执行图片的上传 //1,获取图片的完整路径 返回文件对象 File dest = getAbsPath(session,tempPath,oldName); //2,执行存储 try { multipartFile.transferTo(dest); }catch (IOException e) { return new JsonResult(ResultCode.EXCEPTION,“图片上传失败!原因为” + e.getMessage()); } //3,根据path生成url //获取绝对路径 String absPath = dest.getAbsolutePath(); String url = StringUtils.replace(absPath, “\”, “/”); log.info(“图片路径:” + url); resultMap.put(“url”,url); return new JsonResult(ResultCode.SUCCESS,resultMap); }

/** *

@param path 存储的目录@param oldName 文件名@return 文件对象 */ private File getAbsPath(HttpSession session,String path,String oldName) { Nurse nurse = (Nurse) session.getAttribute(“nurse”); String dateStr = DateUtils.getFileYmd(); if (Objects.nonNull(nurse)) { dateStr = dateStr + “/” + nurse.getNurseId(); } File file = new File(path, dateStr); if(!file.exists()) { file.mkdirs(); } File newFile = new File(file, oldName); return newFile; } }
最新回复(0)