一、创建工具类 Base64.java
package eg.demo.util;
//记得修改包路径
import org.springframework.stereotype.Service;
import sun.misc.BASE64Decoder;
import java.io.File;
import java.io.FileOutputStream;
import java.util.UUID;
//未导入的包自动补全即刻
@Service
public class Base64 {
public String base64(String imageFile) {
String type = imageFile.split(",")[0].split("/")[1].split(";")[0];
imageFile = imageFile.split(",")[1];
BASE64Decoder decoder = new BASE64Decoder();
// Base64解码
byte[] imageByte = null;
try {
imageByte = decoder.decodeBuffer(imageFile);
for (int i = 0; i < imageByte.length; ++i){
if (imageByte[i] < 0) {// 调整异常数据
imageByte[i] += 256;
}
}
} catch (Exception e) {
e.printStackTrace();
}
return Bytes2File(imageByte,type);
}
public static String Bytes2File(byte[] imageByte , String type)
{
String path = null;
try {
int length = imageByte.length;
//追加文件夹
File file = new File("D:/MusicImage");
if(!file.exists()){
file.mkdirs();
}
path = "D:/MusicImage/"+UUID.randomUUID()+ "." + type;
FileOutputStream fos = new FileOutputStream(path);//isAppend如果为true,为追加写入,否则为覆盖写入
fos.write(imageByte,0,length);
fos.close();
path = path.replaceAll("D:/MusicImage/","/upload/");
}catch (Exception e){
e.printStackTrace();
}
return path;
}
}
二、创建配置类 ImageUpLoadConfig.java ,配置虚拟路径
package org.config;
//记得修改包路径
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
@Configuration
public class ImageUpLoadConfig extends WebMvcConfigurerAdapter {
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
//此处为你的绝对路径配置虚拟路径
registry.addResourceHandler("/upload/**").addResourceLocations("file:D:/MusicImage/");
}
}
三、修改application-dev.yml配置信息,根据需要改变文件上传大小限制
此处为了方便,直接使用-1取消上限
tomcat:
max-http-post-size: -1
PS:tomcat与port节点同级
四、前端界面
使用input标签, type = "file"
//图片校验
//在input file内容改变的时候触发事件
$('#upload-file').change(function(){
//获取input file的files文件数组;
//$('#filed')获取的是jQuery对象,.get(0)转为原生对象;
//这边默认只能选一个,但是存放形式仍然是数组,所以取第一个元素使用[0];
var file = $('#upload-file').get(0).files[0];
//创建用来读取此文件的对象
var reader = new FileReader();
//使用该对象读取file文件
reader.readAsDataURL(file);
//读取文件成功后执行的方法函数
reader.onload=function(e){
//读取成功后返回的一个参数e,整个的一个进度事件
console.log(e);
//选择所要显示图片的img,要赋值给img的src就是e中target下result里面
//的base64编码格式的地址
$('#avatar').get(0).src = e.target.result;
// $('#avatar').attr("src","e.target.result");
};
});
五、后端controller层
使用ajax将64位编码后的图片传到后端controller
@RequestMapping("/demo/upLoadFile")
public String insertImage(String imageFile){
Base64 base64 = new Base64();
String path = base64.base64(imageFile);
//debug标记
System.out.println(path);
return path;
}
使用debug模式即可看到返回的path已经从繁杂的64位编码变为简洁的虚拟路径,图片也已经存储到Base64.java配置的绝对路径下