功能描述
点击文件上传框,选中图片时,页面显示选择的图片
需要用ajax将选中的文件发送到后台,后台将文件上传到项目里面,再返回一个图片相对路径
1.前端页面
<p>
<img src="${news.img }" id="displayImg"/>
图片:<input type="file" name = "fimg" id="fileToUpload"/>
</p>
2.脚本
<script type="text/javascript">
$(function(){
//文件上传框值改变时触发
$("#fileToUpload").change(function(){
var upLoadFile = new FormData();//好像是要封装成form类型数据
upLoadFile.append("fimg", $("#fileToUpload")[0].files[0]);//将jquery对象转成dom对象
$.ajax({
url:"news/alterImgPath.do",
dataType:"json",
type:"POST",
data:upLoadFile,
//mimeType:"multipart/form-data",
contentType: false, //不设置内容类型 ,好像是必须的
processData: false,//不处理数据,好像是必须的
success:function(map){
$("#displayImg").attr("src", map.msg);
},
error:function(){
alert("ajax failed");
}
});
})
})
</script>
3 . 后台service层:写了一个上传文件的方法
public String alterImgPath(CommonsMultipartFile fimg) {
String imgPath = null;
if (fimg.getSize() > 0) {
String oldName = fimg.getOriginalFilename();
String newName = UUID.randomUUID().toString() + oldName.substring(oldName.lastIndexOf("."));
File newFile = new File("D:/tools/apache-tomcat-8.0.50/webapps/img/" + newName);
try {
fimg.transferTo(newFile);
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
imgPath = "../img/" + newName;
}
return imgPath;
}
4.controller层
/*
* @ResponseBody: 返回的结果直接响应给页面,不经过视图解析器什么什么的
* 传过来的文件 必须通过注解@RequestParam绑定
*/
@RequestMapping("/alterImgPath.do")
@ResponseBody
public Map<String, String> alterImgPath(@RequestParam(value="fimg")CommonsMultipartFile fimg){
Map<String, String> map = new HashMap<String, String>();
String path = fs.alterImgPath(fimg);
map.put("msg", path);
return map;
}