完成的思绪:
东西: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 = 1G sfu.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.jpg String 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入门教程
以上就是java完成图片上传至服务器的细致内容,更多请关注ki4网别的相干文章!