Java编程之如何通过JSP实现头像自定义上传
Tonytom 人气:0开发概述
本次项目意在实现一种可以在本地选择图片,然后将其上传至服务器指定文件目录下,并可以通过服务器自动生成的临时链接下载到本地的指定目录进行保存,这样数据库就只需要存储对应图片的文件名即可进行正常的显示,以达到上传图片的目的。
开发环境
整体使用了Maven
的开发环境 数据库操作使用的是Mybatis
进行管理 前台页面的显示操作则是通过jsp+servlet
数据库采用mysql
数据库
开发过程
1、JSP前台页面
首先你需要在你的jsp页面中准备好一个图片上传的<form>
表单,一开始<input>
标签中的value值
可以先设置为默认值,到后面连接好数据库,写好servlet之后再进行替换,这里就不在具体展示过程了,直接一步到位。另外本次举例的具体呈现的效果样式如下图所示:
<div class="modal modal-profile" style="display: none;"> <div class="hd"><h4 class="tt" style="margin-left: 10px;">我的资料</h4><a id="a_close" class="close">×</a></div> <div class="bd"> <form class="form-horizontal" action="../usersInfo.do" method="post" enctype="multipart/form-data"> <div class="avatar"><img id="showupimg" src="img/upload/image/<%=usersInfo.getUava()%>" alt="头像"> <a class="upload">点击更换</a><input id="uploadimg" type="file" name="file" accept="image/png, image/jpeg, image/gif, image/jpg" class="upload-input"> <input type="hidden" name="uname" value="<%=usersInfo.getUname()%>"/> </div> <div class="form-group"><label class="control-label">昵称</label> <div class="control-form"><input name="unname" type="text" placeholder="请输入昵称" class="form-control" value="<%=usersInfo.getUnname()%>"><!----></div> </div> <div class="form-group"><label class="control-label">签名</label> <div class="control-form"> <textarea name="signview" rows="5" placeholder="请输入签名,字数不超过100字" class="form-control"><%=usersInfo.getUpersonal()%></textarea> </div> </div> <div class="ft"> <input type="submit" id="btn_save" class="btn btn-primary" value="保存"/> <button type="button" id="btn_cancel" class="btn btn-default">取消</button> </div> </form> </div>
样式图:
JS操作
本来这里想通过ajax来完成的,因为通过servlet重定向会页面时,页面总会闪一下,影响了用户体验,但是由于赶时间,就没有把它改成ajax,以后有时间的话可能会补一段,现在先这样吧。
$("#uploadimg").change(function () { var url, imgbase64; //获取file对象URL if (navigator.userAgent.indexOf("MSIE") >= 1) { // IE url = document.getElementById('uploadimg').value; } else if (navigator.userAgent.indexOf("Firefox") > 0) { // Firefox url = window.URL.createObjectURL(document.getElementById('uploadimg').files.item(0)); } else if (navigator.userAgent.indexOf("Chrome") > 0) { // Chrome url = window.URL.createObjectURL(document.getElementById('uploadimg').files[0]); } // 创建Image对象 var image = new Image(); image.src = url; image.onload = function () { imgbase64 = getBase64Image(image); $("#showupimg").attr("src",image.src); } });
2、数据库的设计
关于数据库表做的其实还是比较简单的,我做的其实是分了两个表,一个Users
表,一个UsersInfo
表。Users表用来存放用户的账号、密码和登录时间;UsersInfo表用来存储对应用户的用户信息,如昵称、头像、性别、年龄等等,这里Users表用不到,所以只展示了UsersInfo表。
数据库表:
实体类:UsersInfo.java
package com.skdsc.domain.login; public class UsersInfo { private String uname; private String unname; private Sex usex; private String uage; private String uava; private String uqq; private String upersonal; public UsersInfo() { } public UsersInfo(String uname, String unname, Sex usex, String uage, String uava, String uqq, String upersonal) { this.uname = uname; this.unname = unname; this.usex = usex; this.uage = uage; this.uava = uava; this.uqq = uqq; this.upersonal = upersonal; } public String getUname() { return uname; } public void setUname(String uname) { this.uname = uname; } public String getUnname() { return unname; } public void setUnname(String unname) { this.unname = unname; } public Sex getUsex() { return usex; } public void setUsex(Sex usex) { this.usex = usex; } public String getUage() { return uage; } public void setUage(String uage) { this.uage = uage; } public String getUava() { return uava; } public void setUava(String uava) { this.uava = uava; } public String getUqq() { return uqq; } public void setUqq(String uqq) { this.uqq = uqq; } public String getUpersonal() { return upersonal; } public void setUpersonal(String upersonal) { this.upersonal = upersonal; } }
3、数据库操作
这里用到的数据库操作主要是两个:findByUserInfoName()
和updateUsersInfo()
UsersMapper
import com.skdsc.domain.login.Users; import com.skdsc.domain.login.UsersInfo; import org.apache.ibatis.annotations.Param; public interface UsersMapper { Users findByUserName(@Param("parUserName") String parUserName); UsersInfo findByUsersInfoName(@Param("parUserName") String parUserName); int updateUtime(@Param("uname") String uname,@Param("newUtime") String newUtime); int updateUsersInfo(@Param("uname") String uname,@Param("newUnname") String newUnname,@Param("newUpersonal") String newUpersonal,@Param("newUava") String newUava); }
UsersMapper.xml
<mapper namespace="com.skdsc.mappers.login.UsersMapper"> <sql id="selStr">uid,uname,upwd,utime</sql> <sql id="selStr1">uname,unname,uage,usex,uava,uqq,upersonal</sql> <resultMap id="newUsersInfo" type="com.skdsc.domain.login.UsersInfo"> <result property="uname" column="uname"/> <result property="unname" column="unname"/> <result property="uage" column="uage"/> <result property="uava" column="uava"/> <result property="uqq" column="uqq"/> <result property="upersonal" column="upersonal"/> <!--嵌套对象标签--> <association property="usex" javaType="com.skdsc.domain.login.Sex"> <id property="sid" column="sid"/> <result property="sname" column="sname"/> </association> </resultMap> <!-- 根据学号查询用户表 --> <select id="findByUserName" resultType="com.skdsc.domain.login.Users"> SELECT <include refid="selStr" /> FROM Users where uname = #{parUserName,jdbcType=VARCHAR} </select> <!-- 根据学号查询用户信息表 --> <select id="findByUsersInfoName" resultType="com.skdsc.domain.login.UsersInfo"> SELECT <include refid="selStr1" /> FROM UsersInfo where uname = #{parUserName,jdbcType=VARCHAR} </select> <!-- 更新最近一次的登录时间 --> <update id="updateUtime"> UPDATE Users SET utime = #{newUtime} where uname = #{uname} </update> <!-- 更新个人资料(头像、昵称、个人签名) --> <update id="updateUsersInfo"> UPDATE UsersInfo <trim prefix="set" suffixOverrides=","> <if test="newUnname !=null">unname = #{newUnname},</if> <if test="newUpersonal !=null">upersonal = #{newUpersonal},</if> <if test="newUava !=null">uava = #{newUava}</if> </trim> WHERE uname = #{uname} </update> </mapper>
4、Servlet
这里主要是先获取<form>
表单提交上来的数据,对数据进行处理,获得其路径以及文件后缀,并利用年月日时分秒+8位随机数生成一个新的文件名,最后通过DownloadImage工具类中的download方法将图片下载到本地的指定目录。
import static com.lazy.servlet.utils.DownloadImage.download; import static com.lazy.servlet.utils.TimeRandom.createOrderCode; @WebServlet("/usersInfo.do") @MultipartConfig public class UsersInfoAction extends HttpServlet { private static final long serialVersionUID = 1L; @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { request.setCharacterEncoding("UTF-8"); String unname = request.getParameter("unname"); String upersonal = request.getParameter("signview"); String uname = request.getParameter("uname"); System.out.println(unname + upersonal + uname); try { //设置基础路径 String basePath = "http://localhost:8080/smartcampus_web_war/center/img/upload/image/"; //获取上传的文件 Part part = request.getPart("file"); //获取请求的信息 String name=part.getHeader("content-disposition"); //获取上传文件的目录 String root=request.getServletContext().getRealPath("/center/img/upload/image"); System.out.println("测试上传文件的路径:"+root); //获取文件的后缀 String str=name.substring(name.lastIndexOf("."), name.length()-1); System.out.println("测试获取文件的后缀:"+str); //生成一个新的文件名,不重复,数据库存储的就是这个文件名,不重复的 String filename=root+"\\"+createOrderCode()+str; System.out.println("测试产生新的文件名:"+filename); //获取上传到本地服务器的图片路径 String strimg = filename.substring(filename.lastIndexOf("\\")+1); String imgsrc = basePath + strimg; System.out.println("测试获取图片名称:"+strimg); //上传文件到指定目录,不想上传文件就不调用这个 part.write(filename); //下载到本地指定目录 download(imgsrc, strimg,"E:\\Studyspaces\\Intellij IDEA\\IdeaProjects\\sk170403\\smartcampus_web\\src\\main\\webapp\\center\\img\\upload\\image"); SqlSession sqlSession = MybatisUtil.getSqlSession(); UsersMapper usersMapper = sqlSession.getMapper(UsersMapper.class); int updateUsersInfoflag = usersMapper.updateUsersInfo(uname,unname,upersonal,strimg); if (updateUsersInfoflag != 0){ sqlSession.commit(); }else { sqlSession.rollback(); } } catch (Exception e) { e.printStackTrace(); } response.sendRedirect("center/zfcenter.jsp"); } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { this.doGet(req, resp); } }
5、工具类
DownloadImage:下载指定路径下的文件到本地指定目录
package com.lazy.servlet.utils; import java.io.File; import java.io.FileOutputStream; import java.io.InputStream; import java.io.OutputStream; import java.net.URL; import java.net.URLConnection; public class DownloadImage { /** * @param args * @throws Exception */ public static void download(String urlString, String filename,String savePath) throws Exception { // 构造URL URL url = new URL(urlString); // 打开连接 URLConnection con = url.openConnection(); //设置请求超时为5s con.setConnectTimeout(5*1000); // 输入流 InputStream is = con.getInputStream(); // 1K的数据缓冲 byte[] bs = new byte[1024]; // 读取到的数据长度 int len; // 输出的文件流 File sf=new File(savePath); if(!sf.exists()){ sf.mkdirs(); } OutputStream os = new FileOutputStream(sf.getPath()+"\\"+filename); // 开始读取 while ((len = is.read(bs)) != -1) { os.write(bs, 0, len); } // 完毕,关闭所有链接 os.close(); is.close(); } }
TimeRandom:生成年月日时分秒+8位随机数
package com.lazy.servlet.utils; import java.text.SimpleDateFormat; import java.util.Date; public class TimeRandom { private static String getNowDate(){ Date date = new Date(); SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMddHHmmss"); return simpleDateFormat.format(date); } private static String getRandom(){ String rand = ""; for (int i = 0; i < 8; i++){ rand = rand + (int)(Math.random()*10); } return rand; } public static String createOrderCode(){ String OrderCode = getNowDate() + getRandom(); return OrderCode; } }
6、最终效果展示
总结
加载全部内容