SSM图片上传:https://blog.csdn.net/weixin_37595711/article/details/85109381
1.html部分
<!DOCTYPE html>
<html lang="en">
<head>
<title>上传图片</title>
</head>
<body>
<input type="file" id="myImage" name="myImage"/>
<button onclick="sent()">sent</button>
</body>
<script type="text/javascript" src="js/jquery.js" ></script>
<script type="text/javascript">
function sent(){
var file=document.getElementById('myImage');
readFile(file);
}
function readFile(file) {
var file = file.files[0];
//判断是否是图片类型
/*if (!/image\/\w+/.test(file.type)) {
alert("只能选择图片");
return false;
}*/
var reader = new FileReader() //新建一个FileReader对象
reader.readAsDataURL(file) //将读取的文件转换成base64格式
reader.onload = function(e) {
var base64Data=e.target.result;
txshow.src = this.result;
console.log(e.target.result) //转换后的文件数据存储在e.target.result中
document.getElementById("data").innerText=this.result.substring(this.result.indexOf(',')+1);
ajaxUploadBase64File(base64Data);
}
}
//ajax异步上传
function ajaxUploadBase64File(base64Data){
var url = "http://localhost:8080/sringmvcphoto/postBase64Img.action";
$.ajax({
url:url,
type:"post",
data:{myPhoto:base64Data},
dataType:"json",
success:function(data){
if(data.success == true){
console.log("上传成功");
}else{
console.log("上传失败");
}
},
error:function(){
console.log("上传失败");
}
});
};
</script>
</html>
2.controller
@RequestMapping(value = "/postBase64Img.action",method = RequestMethod.POST)
public Object base64Img(@RequestParam("myPhoto") String base64Data, HttpServletRequest request) throws JsonProcessingException {
HashMap<String,Object> hashMap=new HashMap<>();
ObjectMapper mapper = new ObjectMapper();
try {
String dataPrix = "";
String data = "";
LOGGER.debug("对数据进行判断");
if(base64Data == null || "".equals(base64Data)){
throw new Exception("上传失败,上传图片数据为空");
}else{
String [] d = base64Data.split("base64,");
if(d != null && d.length == 2){
dataPrix = d[0];
data = d[1];
}else{
throw new Exception("上传失败,数据不合法");
}
}
LOGGER.debug("对数据进行解析,获取文件名和流数据");
String suffix = "";
if("data:image/jpeg;".equalsIgnoreCase(dataPrix)){//data:image/jpeg;base64,base64编码的jpeg图片数据
suffix = ".jpg";
} else if("data:image/x-icon;".equalsIgnoreCase(dataPrix)){//data:image/x-icon;base64,base64编码的icon图片数据
suffix = ".ico";
} else if("data:image/gif;".equalsIgnoreCase(dataPrix)){//data:image/gif;base64,base64编码的gif图片数据
suffix = ".gif";
} else if("data:image/png;".equalsIgnoreCase(dataPrix)){//data:image/png;base64,base64编码的png图片数据
suffix = ".png";
}else{
throw new Exception("上传图片格式不合法");
}
String imgName=UUID.randomUUID().toString();
String tempFileName = imgName + suffix;
LOGGER.debug("生成文件名为:"+tempFileName);
//因为BASE64Decoder的jar问题,此处使用spring框架提供的工具包
byte[] bs = Base64Utils.decodeFromString(data);
try{
File file=null;
//使用apache提供的工具类操作流
String url = request.getSession().getServletContext().getRealPath("/upload");
FileUtils.writeByteArrayToFile(new File(url+"/" + tempFileName), bs);
String pitureUrl=host+tempFileName;
System.out.println(pitureUrl);
hashMap.put("end","OK");
hashMap.put("url",pitureUrl);
}catch(Exception ee){
throw new Exception("上传失败,写入文件失败,"+ee.getMessage());
}
}catch (Exception e){
hashMap.put("end","upload err");
e.printStackTrace();
}
return mapper.writeValueAsString(hashMap);
}
}
3.工具类
package com.utils;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;
import java.io.*;
public class Base64Image {
public static String GetImageStr(String imgFilePath) {// 将图片文件转化为字节数组字符串,并对其进行Base64编码处理
byte[] data = null;
// 读取图片字节数组
try {
InputStream in = new FileInputStream(imgFilePath);
data = new byte[in.available()];
in.read(data);
in.close();
} catch (IOException e) {
e.printStackTrace();
}
// 对字节数组Base64编码
BASE64Encoder encoder = new BASE64Encoder();
return encoder.encode(data);// 返回Base64编码过的字节数组字符串
}
public static boolean GenerateImage(String imgStr, String imgFilePath) {// 对字节数组字符串进行Base64解码并生成图片
if (imgStr == null) // 图像数据为空
return false;
BASE64Decoder decoder = new BASE64Decoder();
try {
// Base64解码
byte[] bytes = decoder.decodeBuffer(imgStr);
for (int i = 0; i < bytes.length; ++i) {
if (bytes[i] < 0) {// 调整异常数据
bytes[i] += 256;
}
}
// 生成jpeg图片
OutputStream out = new FileOutputStream(imgFilePath);
out.write(bytes);
out.flush();
out.close();
return true;
} catch (Exception e) {
return false;
}
}
}
结果