我的图片上传使用form表单,html:
<form action="imagsUp" enctype="multipart/form-data" method="post" >
<img src="img/img_basic.jpg"id="img" style="width:120px;height:110px;float:left;"/> <a id="img_a"> 选择你的新头像--〉</a> <input id="file" name="img_file" onchange="c()" type="file" style="display:none;"><br> <div id="imgcss"class="imgcss"style="float:left;margin-top:-20px;"><i class="icon-plus" id="i"></i></div> <button id="Up" type="submit" value="确定" class="button"style="">确定</button>〈/form>
css
.imgcss{ width:100px;height:100px;border:1px solid #f0f0f0; } .imgcss:hover i{ color:#CCCCFF; background-color:#f0f0f0; } .imgcss i{ font-size:100px;width-size:2px;color:#f0f0f0; } /*图片*/ #img_a{ float:left;margin-top:40px;font-weight:bold;color:#C0C0C0; } #Up{ float:right; height:20px;width:60px;font-size:15px;margin-top:20px; }
js
//这个方法是隐藏的文件上传控件点击方
function c () { var r= new FileReader(); var f=$("#file")[0].files[0]; r.readAsDataURL(f); r.onload=function (e) { $("#i").css('display','none'); $("#imgcss").css("background-image","url("+this.result+")"); $("#imgcss").removeClass("imgcss"); $("#imgcss").css({"background-size":"cover","width":"100px","height":"100px"}); }; } $(document).ready(function() { $("#imgcss").click(function(){ $("#file").click(); });});
FileItemFactory factory = new DiskFileItemFactory(); // 创建文件上传处理器 ServletFileUpload upload = new ServletFileUpload(factory); // 开始解析请求信息 List items = null; try { items = upload.parseRequest(request); } catch (FileUploadException e) { e.printStackTrace(); } // 对所有请求信息进行判断 Iterator iter = items.iterator(); while (iter.hasNext()) { FileItem item = (FileItem) iter.next(); // 信息为普通的格式 if (item.isFormField()) { String fieldName = item.getFieldName(); String value = item.getString(); request.setAttribute(fieldName, value); } // 信息为文件格式 else { String fileName = item.getName(); String suffix = fileName.substring(fileName.lastIndexOf('.')); //图片名 System.out.println("图片名字"+fileName); //后缀名 System.out.println(suffix); int index = fileName.lastIndexOf("\\"); fileName = fileName.substring(index + 1); request.setAttribute("realFileName", fileName); //图片url String basePath = getServletConfig().getServletContext().getRealPath("/")+"img"; System.out.println(basePath); //新文件名 String newFileName = new Date().getTime() + suffix; System.out.println(newFileName); File file = new File(basePath, newFileName); try { item.write(file); int userId = (Integer) request.getSession().getAttribute("id"); System.out.println("userId:" + userId); //存图片信息 imagsTT.ImagsUp(userId, newFileName,basePath); session.setAttribute("imgurl", "img/" + newFileName); System.out.print("用图片返回查询的数据"+"img/" + newFileName); } catch (Exception e) { e.printStackTrace(); } } request.setAttribute("msg","文件上传成功!"); getServletContext().getRequestDispatcher("/My.jsp").forward(request, response); return; }
后台把数据传给数据库,成功后跳转页面,在html页面中用这个<img src="${sessionScope.imgurl}"/>