用ajax来实现添加图片

        大家可能在日常工作中经常遇到这种操作,例如:你要去给用于添加信息的时候经常去给用户添加头像。这时候不只是添加头像那么简单,你给用户选择照片的时候还需要将选择好的照片给回显出来,这个时候,就需要用到我们这个ajax提交照片与数据库进行后台交互的时候了。

        我们想要与数据库进行后台交互,肯定少不了要用到我们的ajax,那么普通的ajax是无法实现这种效果的,我们需要用到Jquery-form.js(可以去官网进行下载:下载的时候不会直接下载,你可以把文本上的内容复制到自己写的js上面点击打开链接)。

        前台:(这里用到了前台与后台的数据库交互,所以我们需要用到了success从后台获取数据,从百度上收不到,这是自己的实战经验,我在后台发现好像只能用hashmap的返回值,如有其它的,希望大家通过评论区告诉我一下)

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
<script type="text/javascript" src="<%=request.getContextPath() %>/js/jquery-1.8.2.js"></script>
<script type="text/javascript" src="<%=request.getContextPath() %>/js/jquery-form.min.js"></script>
<style>


/**按钮样式**/
.file {
    position: relative;
    display: inline-block;
    background: #D0EEFF;
    border: 1px solid #99D3F5;
    border-radius: 4px;
    padding: 4px 12px;
    overflow: hidden;
    color: #1E88C7;
    text-decoration: none;
    text-indent: 0;
    line-height: 20px;
}
.file input {
    position: absolute;
    font-size: 100px;
    right: 0;
    top: 0;
    opacity: 0;
}
.file:hover {
    background: #AADFFD;
    border-color: #78C3F3;
    color: #004974;
    text-decoration: none;
}
</style>
<script type="text/javascript">
	function isPictrue(target){
		var fileSize = 0;
		var filetypes = [  ".GIF", ".gif", ".JPEG",".jpeg",".JPG",".jpg",
				".PNG", ".png", ];
		var filepath = target.value;
		
		if (filepath) {
			
			var isnext = false;
			
			var fileend = filepath.substring(filepath.lastIndexOf("."));
			for (var i = 0; i < filetypes.length; i++) {
				
				if (filetypes[i] == fileend) {
					isnext = true;
					break;
				}
			}
			if (!isnext) {
				alert("不接受此文件类型!");
				target.value = "";
				return ;
			}
		} else {
			alert("请选择图片!");
			return ;
		}
		
		
	}
	function toHuiXian(target){
		isPictrue(target);
		 var b={
				 url:"<%=request.getContextPath() %>/thing/toHuiXian.action",
				 type:"post",
				 dataType:"json",
				 success:function(mes){
					 showResponse(mes);
				 }   
				 
		 };
		$("#headImgform").ajaxSubmit(b);
		
	}
	
	function showResponse(mes){  
	  $("#im").attr("src","<%=request.getContextPath() %>/"+mes.address);
	}  
</script>
</head>
<body>
	<img alt="" width="100px" height="50px" id="im" src=""><p></p>选择图片:
		 <form action="" id="headImgform" method="post" enctype="multipart/form-data">
			
			<a href="javascript:;" class="file" style="visibility:true">选择文件
		   <input  name="multFile" type="file" onchange="toHuiXian(this)">
		</a>
		</form>
</body>
</html>

后台代码

@RequestMapping("toHuiXian")
	@ResponseBody
	public HashMap<String,Object> toHuiXian(MultipartFile multFile,HttpServletRequest req){
		
		String upFile = Upload.upFile(multFile, req);
		System.out.println(upFile);
		String b=upFile.substring(upFile.indexOf("image"));
		System.out.println(b);
		HashMap<String, Object> hashMap = new HashMap<>();
		hashMap.put("address", b);
		return hashMap;
	}

Upload的工具类:

public static String upFile(MultipartFile file, HttpServletRequest req) {			
			
			// 获取文件名
			String fileName = file.getOriginalFilename();
			
			// 获取文件的后缀名
			String suffixName = fileName.substring(fileName.lastIndexOf("."));
			//自定义   生成随机文件名
			fileName = UUID.randomUUID() + suffixName;
			//获取项目全路径
			String realPath = req.getServletContext().getRealPath("/");
			System.out.println(realPath);
			//创建日期文件夹路径
			String datePath = new SimpleDateFormat("yyyyMMdd").format(new Date());
			//文件全路径
			String fileAllPath = "image" +File.separator + datePath +File.separator + fileName;
			//上传文件全路径
			File dest = new File(realPath + File.separator + fileAllPath);

			// 检测是否存在目录  没有则创建
			if (!dest.getParentFile().exists()) {
				dest.getParentFile().mkdirs();
			}
			
			try {
				file.transferTo(dest);
			} catch (Exception e) {
				e.printStackTrace();
				return "fial";
			}
			
			return fileAllPath;		
		
	}
这里有一个细节:因为我们做的是用户的头像回显,而不是放在数据中,所以不需要持久化,我们把它放在eclipse中Tomcat自动开启的空间,当我们重新部署的时候就会自动清除,简单,快捷。



猜你喜欢

转载自blog.csdn.net/qq_42430767/article/details/80768642