页面代码:
<!DOCTYPE html>
<html lang="en"><head>
<meta http-equiv="Content-Type" content="text/html;charset=UTF-8">
<script src="jquery-1.7.2.min.js"></script>
<script src="ajaxfileupload.js"></script>
<title>demo</title>
<style>
#box1 {
border: 1px dashed #666;
width: 150px;
height: 150px;
display: flex;
justify-content: center;
align-items: center;
box-shadow: 0 0 8px 5px rgba(163, 117, 140, 0.64);
}
</style>
</head>
<body>
选择图片:<input type="file" id="logo" name="logo" onChange="showImage()" value="logo"/>
<img id="box1"></img>
<input type="button" id="sure" value="生成二维码"/><br/><br/>
</body>
<script>
$("#sure").on('click',function(){
if($("#logo").val()==""){
alert("请先选择logo图片!");
return;
}
//logo上传
$.ajaxFileUpload({
type : "post",
url : "xxxxx",//后台接收url
secureuri:false,
fileElementId: 'logo', //file标签的id
data : { },
dataType : "json",
success : function(data,status) {
alert("success");
},
error: function (data, status, e){ //服务器响应失败处理函数
alert(e+"上传错误");
}
});
});
function showImage() {
var imgFile = document.getElementById('logo').files[0];
var fr = new FileReader();
fr.onload = function () {
$('#box1').html("<img id=\"box2\" src=\"\">");
console.log(fr.result);
document.getElementById('box1').src = fr.result;
};
fr.readAsDataURL(imgFile);
}
</script>
</html>
java代码:
MultipartRequest multRequ = (MultipartRequest) req;
MultipartFile file = multRequ.getFile("logo");
if (file == null) {
file = multRequ.getFile("logo");
}
File logoFile = new File("文件名");
try {
file.transferTo(logoFile);
} catch (IllegalStateException | IOException e1) {
e1.printStackTrace();
}
logoFile 就是得到的图片文件