controller层
import org.junit.platform.commons.util.StringUtils;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import sun.misc.BASE64Encoder;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLEncoder;
import java.util.UUID;
/**
* 图片上传以及回显 base64
*/
//@RestController("/manage/Icon")
@RestController
@RequestMapping("/manage/Icon")
public class FileUploadController {
// InputStream inputStream = null;
// byte[] data = null;
// try {
// inputStream = new FileInputStream(imgPath);
// data = new byte[inputStream.available()];
// inputStream.read(data);
// inputStream.close();
// } catch (
// IOException e) {
// e.printStackTrace();
// }
// // 加密
// BASE64Encoder encoder = new BASE64Encoder();
// return encoder.encode(data);
/**
* @Description 把base64字符串转换成图片文件保存, 并返回url接口
* 前端已经将图片转成了base64位的字符串 iconStoreroom.getIconUrl() 一般情况下是这样
* 因为本项目没有前端 我们使用下面一个方法进行测试
*/
@ResponseBody
@RequestMapping(value = "/saveBase64File", method = RequestMethod.POST)
public ResultEntity saveBase64File(@RequestBody IconStoreroom iconStoreroom) {
ResultEntity resultEntity = new ResultEntity();
String iconAbsolutePath = YmlUtils.getCommonYml("file.icon.path") + "";
String iconName = UUID.randomUUID().toString();
String suffixName = iconStoreroom.getSuffixName();
if (StringUtils.isBlank(suffixName)) {
iconStoreroom.setSuffixName(".png");
}
if (StringUtils.isBlank(iconStoreroom.getIconUrl())) {
throw new ParameterException("请选择上传的文件");
}
ImgUtil.base64ToImg(iconStoreroom.getIconUrl(), iconName, iconAbsolutePath, iconStoreroom.getSuffixName());
String iconUrl = "/manage/Icon/getIcon?newFileName=" + iconName + iconStoreroom.getSuffixName();
resultEntity.setData(iconUrl);
return resultEntity;
}
/**
* @Description 把base64字符串转换成图片文件保存, 并返回url接口
* 上传图片
*/
@ResponseBody
@RequestMapping(value = "/toSaveBase64Photo", method = RequestMethod.POST)
public ResultEntity toSaveBase64Photo() {
//以下将图片转换成base64位字符串
//磁盘中存在的文件(注意我这里是磁盘中存在的文件)
//"C:\Users\Administrator\Desktop\图片\icon\0a55f653-ae01-49cb-835e-35be7b7b6a03.png"
String imgPath = "C:" + File.separator + "Users" + File.separator + "Administrator" + File.separator + "Desktop" + File.separator + "图片" + File.separator + "icon" + File.separator + "0a55f653-ae01-49cb-835e-35be7b7b6a03.png";
// C:\Users\Administrator\Desktop\1
// String imgPath = "C:" + File.separator + "Users" + File.separator + "Administrator" + File.separator + "Desktop" + File.separator + "1" + File.separator+ "activiti.docx";
IconStoreroom iconStoreroom = new IconStoreroom();
InputStream inputStream = null;
byte[] data = null;
try {
inputStream = new FileInputStream(imgPath);
data = new byte[inputStream.available()];
inputStream.read(data);
inputStream.close();
} catch (
IOException e) {
e.printStackTrace();
}
// 加密
BASE64Encoder encoder = new BASE64Encoder();
//图片转换后的base64位字符串
String encode = encoder.encode(data);
ResultEntity resultEntity = new ResultEntity();
String iconAbsolutePath = YmlUtils.getCommonYml("file.icon.path") + "";
String iconName = UUID.randomUUID().toString();
iconStoreroom.setSuffixName(".png");
ImgUtil.base64ToImg(encode, iconName, iconAbsolutePath, iconStoreroom.getSuffixName());
String iconUrl = "/manage/Icon/getIcon?newFileName=" + iconName + iconStoreroom.getSuffixName();
resultEntity.setData(iconUrl);
return resultEntity;
}
@ResponseBody
@RequestMapping(value = "/toSaveBase64File", method = RequestMethod.POST)
public ResultEntity toSaveBase64File(@RequestBody IconStoreroom iconStoreroom) {
//以下将图片转换成base64位字符串
//磁盘中存在的文件(注意我这里是磁盘中存在的文件)
String FilePath = "C:" + File.separator + "Users" + File.separator + "Administrator" + File.separator + "Desktop" + File.separator + "1" + File.separator+ "activiti.docx";
InputStream inputStream = null;
byte[] data = null;
try {
inputStream = new FileInputStream(FilePath);
data = new byte[inputStream.available()];
inputStream.read(data);
inputStream.close();
} catch (
IOException e) {
e.printStackTrace();
}
// 加密
BASE64Encoder encoder = new BASE64Encoder();
//图片转换后的base64位字符串
String encode = encoder.encode(data);
ResultEntity resultEntity = new ResultEntity();
String iconAbsolutePath = YmlUtils.getCommonYml("file.icon.path") + "";
String iconName = UUID.randomUUID().toString();
ImgUtil.base64ToImg(encode, iconName, iconAbsolutePath, iconStoreroom.getSuffixName());
String iconUrl = "/manage/Icon/getIcon?newFileName=" + iconName + iconStoreroom.getSuffixName();
resultEntity.setData(iconUrl);
return resultEntity;
}
/**
* @Description 图片下载接口,可用作回显
**/
@RequestMapping(value = "/getIcon", method = {RequestMethod.GET, RequestMethod.POST})
public ResponseEntity<byte[]> getFile(HttpServletRequest request, HttpServletResponse response) {
String fileName = request.getParameter("newFileName");
if (fileName != null) {
String a[] = {"../", "/etc", " ", ":"};
for (String t : a) {
if (fileName.contains(t)) {
throw new BusinessException("非法文件");
}
}
}
File file = new File(YmlUtils.getCommonYml("file.icon.path") + File.separator + fileName);
if (!file.exists()) {
throw new ParameterException("照片丢失");
}
InputStream is = null;
byte[] body = null;
try {
String downloadFileName = URLEncoder.encode(fileName, "UTF-8");
is = new FileInputStream(file);
body = new byte[is.available()];
is.read(body);
HttpHeaders headers = new HttpHeaders();
headers.add("Content-Disposition", "attchement;filename=" + downloadFileName);
headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
HttpStatus statusCode = HttpStatus.OK;
ResponseEntity<byte[]> entity = new ResponseEntity<byte[]>(body, headers, statusCode);
return entity;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
}
工具类层
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;
import javax.imageio.ImageIO;
import javax.imageio.ImageReader;
import javax.imageio.stream.ImageInputStream;
import java.io.*;
import java.util.Iterator;
public class ImgUtil {
public static void main(String[] args) {
String s = imgTobase64("F:\\皮卡丘.jpg");
//String base64Strtp = base64ToImg(s, "base64Strtp","F:\\", ".jpg");
//System.out.println(base64Strtp);
}
/**
* 图片转base64字符串
*
* @param imgPath
* @return
*/
public static String imgTobase64(String imgPath) {
InputStream inputStream = null;
byte[] data = null;
try {
inputStream = new FileInputStream(imgPath);
data = new byte[inputStream.available()];
inputStream.read(data);
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
// 加密
BASE64Encoder encoder = new BASE64Encoder();
return encoder.encode(data);
}
/**
* @param imgBase64Str 图片base64字符串
* @param imgName 图片名称
* @param saveTopath 要保存到的路径
* @param imgSuffixName 图片后缀名
* @return java.lang.String 图片的保存绝对路径
* @Author lousk
* @Description 把base64图片转成图片文件并保存
* @Date 2020/7/31
* @Time 17:04
*/
public static String base64ToImg(String imgBase64Str, String imgName, String saveTopath, String imgSuffixName) {
//创建文件夹
File dir = new File(saveTopath);
if (!dir.exists()) {// 判断目录是否存在
dir.mkdir();
}
//========================================
BASE64Decoder decoder = new BASE64Decoder();
// 创建流
OutputStream out = null;
//Base64解码
byte[] b = new byte[0];
//图片完整路径 注意:目录下一定要加一个文件格式不然图片字节输出不了
String elbowPhotoImgpath = saveTopath + File.separator + imgName + imgSuffixName;
try {
b = decoder.decodeBuffer(imgBase64Str);
for (int i = 0; i < b.length; ++i) {
if (b[i] < 0) {
//调整异常数据
b[i] += 256;
}
}
out = new FileOutputStream(elbowPhotoImgpath);
out.write(b);
out.flush();
} catch (IOException e) {
e.printStackTrace();
} finally {
// 关闭流
if (null != out) {
try {
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return elbowPhotoImgpath;
}
public static String getFormatName(byte[] buf) throws IOException {
InputStream imageStream = new ByteArrayInputStream(buf);
try (ImageInputStream imageInputStream = ImageIO.createImageInputStream(imageStream)) {
Iterator<ImageReader> imageReadersList = ImageIO.getImageReaders(imageInputStream);
if (imageReadersList.hasNext()) {
ImageReader reader = imageReadersList.next();
return reader.getFormatName();
}
}
return null;
}
}
配置类层
import com.jh.util.YmlUtils;
import org.springframework.context.annotation.Configuration;
import org.springframework.format.FormatterRegistry;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.validation.MessageCodesResolver;
import org.springframework.validation.Validator;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.HandlerMethodReturnValueHandler;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.config.annotation.*;
import java.util.List;
@Configuration
public class UploadConfig implements WebMvcConfigurer {
// @Value("${file.icon.path}")
// private String uploadUrl;
/***告诉spring 静态文件访问地址
* 功能说明:配置静态访问资源
* 文件访问地址配置
* 参考地址 https://blog.csdn.net/taiguolaotu/article/details/105405174
* @param registry registry
* @return void
*/
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
String iconAbsolutePath = YmlUtils.getCommonYml("file.icon.path").toString();
// D://temp//icon
//指定盘符 回显需要这么写(windows环境)
registry.addResourceHandler("/icon/**").addResourceLocations("file:D:/temp/icon/"); //行得通
// registry.addResourceHandler("/icon/**").addResourceLocations("file:D://temp//icon//"); //行的通
// registry.addResourceHandler("/icon/**").addResourceLocations("file:" + iconAbsolutePath); //行不通
// registry.addResourceHandler("/icon/**").addResourceLocations("file:+ iconAbsolutePath"); //行不通
//=====================================================================================================
// linux环境下
/***告诉spring 静态文件访问地址
* 功能说明:配置静态访问资源
* 文件访问地址配置
* @param registry registry
* @return void
*/
// @Override
// public void addResourceHandlers(ResourceHandlerRegistry registry) {
// registry.addResourceHandler("/static/upload/**").addResourceLocations("file:" + uploadUrl);
// }
// application.yml 配置文件
// zmj:
// uploadPhoto: /root/photo/src/main/resources/static/upload
}
@Override
public void addCorsMappings(CorsRegistry corsRegistry) {
}
@Override
public void addViewControllers(ViewControllerRegistry viewControllerRegistry) {
}
@Override
public void configureViewResolvers(ViewResolverRegistry viewResolverRegistry) {
}
@Override
public void addArgumentResolvers(List<HandlerMethodArgumentResolver> list) {
}
@Override
public void addReturnValueHandlers(List<HandlerMethodReturnValueHandler> list) {
}
@Override
public void configureMessageConverters(List<HttpMessageConverter<?>> list) {
}
@Override
public void extendMessageConverters(List<HttpMessageConverter<?>> list) {
}
@Override
public void configureHandlerExceptionResolvers(List<HandlerExceptionResolver> list) {
}
@Override
public void extendHandlerExceptionResolvers(List<HandlerExceptionResolver> list) {
}
@Override
public Validator getValidator() {
return null;
}
@Override
public MessageCodesResolver getMessageCodesResolver() {
return null;
}
@Override
public void configurePathMatch(PathMatchConfigurer pathMatchConfigurer) {
}
@Override
public void configureContentNegotiation(ContentNegotiationConfigurer contentNegotiationConfigurer) {
}
@Override
public void configureAsyncSupport(AsyncSupportConfigurer asyncSupportConfigurer) {
}
@Override
public void configureDefaultServletHandling(DefaultServletHandlerConfigurer defaultServletHandlerConfigurer) {
}
@Override
public void addFormatters(FormatterRegistry formatterRegistry) {
}
@Override
public void addInterceptors(InterceptorRegistry interceptorRegistry) {
}
}