实现的思路:
工具:MySQL,eclipse
首先,在MySQL中创建了两个表,一个t_user表,用来存放用户名,密码等个人信息,一个t_touxiang表,用来存放上传的图片在服务器中的存放路径,以及图片名字和用户ID,T_touxiang表中的用户ID对应了t_user中的id。
t_user表SQL:
DROP TABLE IF EXISTS `t_user`;CREATE TABLE `t_user` ( `id` int(10) NOT NULL AUTO_INCREMENT, `username` varchar(20) NOT NULL, `password` varchar(255) NOT NULL, PRIMARY KEY (`id`), UNIQUE KEY `username` (`username`)) ENGINE=InnoDB AUTO_INCREMENT=22 DEFAULT CHARSET=utf8;
T_touxiang表SQL:
DROP TABLE IF EXISTS `t_touxiang`;CREATE TABLE `t_touxiang` ( `id` int(10) NOT NULL AUTO_INCREMENT, `image_path` varchar(255) DEFAULT NULL, `user_id` int(11) DEFAULT NULL, `old_name` varchar(255) DEFAULT NULL, PRIMARY KEY (`id`), KEY `img_user` (`user_id`), CONSTRAINT `img_user` FOREIGN KEY (`user_id`) REFERENCES `t_user` (`id`)) ENGINE=InnoDB AUTO_INCREMENT=6 DEFAULT CHARSET=utf8;
首先,写一个UploadServlet.java,用来处理图片文件的上传,并将图片路径,图片名称等信息存放到t_touxiang数据表中,代码如下:
@WebServlet("/UploadServlet.do")public class UploadServlet extends HttpServlet { private static final long serialVersionUID = 1L; protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {// 判断上传表单是否为multipart/form-data类型HttpSession session = request.getSession();User user = (User) session.getAttribute("user"); // 在登录时将 User 对象放入了会话中if (ServletFileUpload.isMultipartContent(request)) { try {// 1. 创建DiskFileItemFactory对象,设置缓冲区大小和临时文件目录DiskFileItemFactory factory = new DiskFileItemFactory();// System.out.println(System.getProperty("java.io.tmpdir"));//默认临时文件夹// 2. 创建ServletFileUpload对象,并设置上传文件的大小限制。ServletFileUpload sfu = new ServletFileUpload(factory);sfu.setSizeMax(10 * 1024 * 1024);// 以byte为单位 不能超过10M 1024byte = // 1kb 1024kb=1M 1024M = 1Gsfu.setHeaderEncoding("utf-8");// 3.// 调用ServletFileUpload.parseRequest方法解析request对象,得到一个保存了所有上传内容的List对象。@SuppressWarnings("unchecked")List<FileItem> fileItemList = sfu.parseRequest(request);Iterator<FileItem> fileItems = fileItemList.iterator();// 4. 遍历list,每迭代一个FileItem对象,调用其isFormField方法判断是否是上传文件while (fileItems.hasNext()) { FileItem fileItem = fileItems.next(); // 普通表单元素 if (fileItem.isFormField()) {String name = fileItem.getFieldName();// name属性值String value = fileItem.getString("utf-8");// name对应的value值System.out.println(name + " = " + value); } // <input type="file">的上传文件的元素 else {String fileName = fileItem.getName();// 文件名称System.out.println("原文件名:" + fileName);// Koala.jpgString suffix = fileName.substring(fileName.lastIndexOf('.'));System.out.println("扩展名:" + suffix);// .jpg// 新文件名(唯一)String newFileName = new Date().getTime() + suffix;System.out.println("新文件名:" + newFileName);// image\1478509873038.jpg// 5. 调用FileItem的write()方法,写入文件File file = new File("D:/lindaProjects/mySpace/wendao/WebContent/touxiang/" + newFileName);System.out.println(file.getAbsolutePath());fileItem.write(file);// 6. 调用FileItem的delete()方法,删除临时文件fileItem.delete();/* * 存储到数据库时注意 1.保存源文件名称 Koala.jpg 2.保存相对路径 * image/1478509873038.jpg * */if (user != null) { int myid = user.getId(); String SQL = "INSERT INTO t_touxiang(image_path,user_id,old_name)VALUES(?,?,?)"; int rows = JdbcHelper.insert(SQL, false, "touxiang/" + newFileName, myid, fileName); if (rows > 0) {session.setAttribute("image_name", fileName);session.setAttribute("image_path", "touxiang/" + newFileName);response.sendRedirect(request.getContextPath() + "/upImage.html"); } else { }} else { session.setAttribute("loginFail", "请登录"); response.sendRedirect(request.getContextPath() + "/login.html");} }} } catch (FileUploadException e) {e.printStackTrace(); } catch (Exception e) {e.printStackTrace(); }} }}
在完成图片上传并写入数据库的同时,将图片路径通过session的方式发送到HTML界面
<!DOCTYPE html><html><head><meta charset="UTF-8"><title>更换头像</title></head><body> <formaction="UploadServlet.do" method="post"enctype="multipart/form-data"> 本地目录:<inputtype="file" name="uploadFile"> <img src="${image_path}" width="200" height="200"> <inputtype="submit" value="上传头像"/> </form></body></html>
至此,图片上传数据库和本地服务器已经实现。
推荐教程:java入门教程