HTML代码
<body>
<div id="d" style="width: 200px;height: 200px;border: 1px solid #000000;">
<img id="img" src="../img/moren.jpeg" style="width: 200px;height: 200px;">
</div>
<form method="post" enctype="multipart/form-data" id="f1">
<input type="file" name="file" value="" id="file" onchange="getimage(this)">
<input type="button" value="submit" id="sub">
</form>
</body>
JQuery代码
<script>
//图片预览
function getimage(obj) {
var file = obj.files[0];
var reader = new FileReader();
reader.onload = function (e) {
var img = document.getElementById("img");
img.src = e.target.result;
}
reader.readAsDataURL(file)
}
//图片异步上传
$('#sub').click(function(){
var formdata=new FormData($('#f1')[0]);
if($('#file').val()==''){
alert("请选择图片哦");
return false;
}
$.ajax({
type:"post",
url:"${pageContext.request.contextPath}/photo/file.do",
data:formdata,
//ajax2.0可以不用设置请求头,但是jq帮我们自动设置了,这样的话需要我们自己取消掉
contentType:false,
//取消帮我们格式化数据,是什么就是什么
processData:false,
success:function(data){
alert("修改成功");
$('#file').val("");
},
error:function(){
alert("更换错误!!!")
}
})
})
控制器层代码
@RequestMapping("/file")
@ResponseBody
public String fileUpload(@RequestParam("file") MultipartFile fileImage) throws IOException {
final String imagePathRoot = "D:\\大三项目\\DengLv_XM\\WebContent\\img\\";
File file = new File(imagePathRoot);//在D盘创建图片文件
if (!file.exists()) {
file.mkdirs();
}
//获取图片名字
String fileName = fileImage.getOriginalFilename();
String fileType = fileName.substring(fileName.lastIndexOf("."));
String uuid = UUID.randomUUID().toString().replace("-", "");
String imageFilePath = imagePathRoot + uuid + fileType;
fileImage.transferTo(new File(imageFilePath));
boolean res= photoMapper.insertPhoto(new Photo(null,fileName,imageFilePath));
return "a";
}