版权声明:如需转载,请写明出处 https://blog.csdn.net/weixin_43113679/article/details/89423054
从头开始
前端
<script type="text/javascript">
// 选择图片显示
function imgChange(obj) {
//获取点击的文本框
var file =document.getElementById("file");
var imgUrl =window.URL.createObjectURL(file.files[0]);
var img =document.getElementById('imghead');
img.setAttribute('src',imgUrl); // 修改img标签src属性值
};
</script>
//因为牵扯到上传图片,form表单一定要有 enctype="multipart/form-data",因为上传立马显示
//还不经过后端,所以accept="image/*"
<form action="url" method="post" enctype="multipart/form-data">
<img id="imghead" src="${sessionScope.userImage}" width="150px" height="150px" />
<input type="file"name="file"id="file" accept="image/*" "imgChange(this);"/>
</form>
当从前端传输到后端文件或图片后,后端
@RequestMapping(value="changMesg" ,method=RequestMethod.POST)
public String changMesg(MultipartFile file, HttpServletRequest request) throws Exception{
if(file!=null){
String originalName =file.getOriginalFilename();
//获取文件.再的位置,好组成新的名称时就直接在末尾添加上格式就行了
int index =originalName.lastIndexOf(".");
//组成一个新的图片名称,用uuid这样避免重复
String newFileName=UUID.randomUUID()+originalName.substring(index,originalName.length());
//获取应用所在的服务的文件路径
ServletContext application =session.getServletContext();
String path=application.getRealPath("/");
File imagFile =new File(path+"uploadimage/"+newFileName);
//写到指定路径了
file.transferTo(imagFile);
//现在图片已经上传到Tomcat的此项目名下的uploadimage文件夹下
}
//这时候如果大家刷新项目,项目下的uploadimage下的图片也不会有,但是如果你去Tomcat中查找肯定能找到,因为你上传到了服务器端上,所以只能在服务器端上查看,不过不要紧,不影响回显
我在这犯了一个错误
我让它在jsp上的src里面写的是服务端的绝地地址,比如:D:/…
肯定显示不出来,一开始以为是静态资源拦截,我又查看了下,没有
最后想起用request.getContextPath()
session.setAttribute("userImage",request.getContextPath()+"/"+imagePath+imageName);
这样前端写的
<img src ="${sessionScope.userImage}"/>
就能显示图片了