我的图片上传使用form表单,html:
- 选择你的新头像--〉
- 确定



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);//图片urlString 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}"/>