Java Web使用ajax技术实现头像上传功能

所需js插件

在这里插入图片描述

界面设计

<div class="pic-box">
		<input class="fileInput" id="file" type="file" name="image" onchange="upload()">
</div>

ajax内容

		function upload() {
				var filename = $("#file").val();
				var username = "${USER_SESSION.username}";
				$.ajaxFileUpload({
				          url : "<%=basePath%>user/fileUpload.action", 
				          fileElementId : 'file', //文件上传空间的id属性 
				          type : 'post',
				          data:{"username":username,"image":filename},
				          dataType : 'json', //返回值类型 
				          success:function(data){
				          	console.log(data);
				          	alert("头像更新成功");         	
						}
					});
				window.location.reload();
				}

java代码

	   // 头像上传
		@RequestMapping("/fileUpload.action")
		@ResponseBody
		public String upload(String username, @RequestParam(value = "image") MultipartFile file,
				HttpServletRequest request) {
			// 保存数据库的路径
			String sqlPath = null;
			// 定义文件保存的本地路径
			String localPath = null;
			// 定义 文件名
			String filename = null;
			if (!file.isEmpty()) {
				localPath = request.getServletContext().getRealPath("/upload/images/");
				File filePath = new File(localPath);
				if (!filePath.exists()) {
					filePath.mkdirs();
				}
				// 生成uuid作为文件名称
				// String uuid = UUID.randomUUID().toString().replaceAll("-", "");
				// 获得文件类型(可以判断如果不是图片,禁止上传)
				String contentType = file.getContentType();
				// 获得文件后缀名
				String suffixName = contentType.substring(contentType.indexOf("/") + 1);
				// 得到 文件名
				filename = username + "." + suffixName;
				// 文件保存路径
				try {
					file.transferTo(new File(localPath + filename));
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
			System.out.println(localPath);
			// 把图片的相对路径保存至数据库
			sqlPath = "images/" + filename;
			System.out.println(sqlPath);
			int recordNum = userService.addImage(username, sqlPath);
			if (recordNum > 0) {
				return "ok";
			} else {
				return "error";
			}
		}

数据库设计

在这里插入图片描述
在这里插入图片描述

实现效果

点击上传头像,弹出文件选择窗口,选择图片,实现图片上传
在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/bgyuan_csdn/article/details/88651956
今日推荐