springmvc结合ajax实现跨域上传文件

本方法的思路是:先在前端利用FileReader将图片转换成base64编码,然后将编码字符串形式传递到后台(前提是服务端设置了允许跨域),后端再把base64编码转换成图片。

前端代码:

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<script type="text/javascript" src="js/jquery-3.1.1.min.js"></script>
</head>
<body>
<input type="file" name="file" id="file">
<img id="testImg" style="max-height: 300px; height: 8em; min-8em;">
<textarea id="testArea" style="display: block; 100%;height: 30em;"></textarea>
<input id="btnTest" type="button" value="提交base" />
<script type="text/javascript">
$(function() {
//点击图片上传方法
$("#btnTest").click(function () {
var fileName = $("#file").val();
var imageType = fileName.substring(fileName.length - 3);
var imgData = $("#testArea").val();
var index = imgData.indexOf("base64,");
var imageContent = imgData.substring(index + 7);
if (ss == "jpg" || ss == "png" || ss == "gif"||ss=="bmp") {
$.ajax({
url: "http://127.0.0.1:8080/uploadPic",
type: "post",
dataType: "json",
data: {"userid" : 1224,
"imageContents" : imageContent,
"imageType" : imageType
},
async: false,
success: function (result) {
}
});
}
});

//选择图片方法
$("#file").change(function(){
run(this, function (data) {
$('#testImg').attr('src', data);
$('#testArea').val(data);
});
});

/*将选择的图片转换成base64*/
/*input_file:文件按钮对象*/
/*get_data: 转换成功后执行的方法*/
function run(input_file, get_data) {
/*input_file:文件按钮对象*/
/*get_data: 转换成功后执行的方法*/
if (typeof (FileReader) === 'undefined') {
alert("抱歉,你的浏览器不支持 FileReader,不能将图片转换为Base64,请使用现代浏览器操作!");
} else {
try {
/*图片转Base64 核心代码*/
var file = input_file.files[0];
//这里我们判断下类型如果不是图片就返回 去掉就可以上传任意文件
if (!/image/w+/.test(file.type)) {
alert("请确保文件为图像类型");
return false;
}
var reader = new FileReader();
reader.onload = function () {
get_data(this.result);
}
reader.readAsDataURL(file);
} catch (e) {
alert('图片转Base64出错啦!' + e.toString())
}
}
}
});
</script>
</body>
</html>

后台就是标准的springmvc代码

/**
* 保存上传图片,返回上传图片名称(不包含格式)
* @param file
* @return 图片路径
* @throws FileNotFoundException
* @throws IOException
*/
@RequestMapping(value = "/uploadPic")
@ResponseBody
public Object upload(@RequestParam("imageContents") String imgStr, @RequestParam("imageType") String imgType, @RequestParam("userid") int userid) {
try {
/* String imgFile = "F://image//Koala.jpg";// 待处理的图片
InputStream in = null;
byte[] data = null;
//读取图片字节数组
try
{
in = new FileInputStream(imgFile);
data = new byte[in.available()];
in.read(data);
in.close();
}
catch (IOException e)
{
e.printStackTrace();
}
//对字节数组Base64编码
BASE64Encoder encoder = new BASE64Encoder();
String localImgStr = encoder.encode(data);//返回Base64编码过的字节数组字符串
if (localImgStr.equals(imgStr)) {
System.out.println("一样");
} else {
System.out.println("不一样");
}*/
/********************************************************/
//设定本地路径
String realPath = System.getProperty("user.dir");
realPath += "//temp" + "." + imgType;
byte[] b = Base64.decodeBase64(new String(imgStr).getBytes());
for(int i=0;i<b.length;++i)
{
if(b[i]<0)
{//调整异常数据
b[i]+=256;
}
}
//生成图片
OutputStream out = new FileOutputStream(realPath);
out.write(b);
out.flush();
out.close();
/* String usericon = systemService.uploadPic(realPath);*/
User user = new User();
user.setId(userid);
user.setUsericon("1111");
userService.updateByPrimaryKeySelective(user);
//更新数据库
} catch (IOException e) {
e.printStackTrace();
return false;
}
return true;
}

原文地址:https://www.cnblogs.com/michaelShao/p/6072677.html