Java实现图片上传到服务器,并把上传的图片读取出来

在很多的网站都可以实现上传头像,可以选择自己喜欢的图片做头像,从本地上传,下次登录时可以直接显示出已经上传的头像,那么这个是如何实现的呢?

 

下面说一下我的实现过程(只是个人实现思路,实际网站怎么实现的不太清楚)

实现的思路:

工具:MySQL,eclipse

首先,在MySQL中创建了两个表,一个t_user表,用来存放用户名,密码等个人信息,

一个t_touxiang表,用来存放上传的图片在服务器中的存放路径,以及图片名字和用户ID,

T_touxiang表中的用户ID对应了t_user中的id。

 

t_user表SQL:

 
  1. DROP TABLE IF EXISTS `t_user`;

  2. CREATE TABLE `t_user` (

  3. `id` int(10) NOT NULL AUTO_INCREMENT,

  4. `username` varchar(20) NOT NULL,

  5. `password` varchar(255) NOT NULL,

  6. PRIMARY KEY (`id`),

  7. UNIQUE KEY `username` (`username`)

  8. ) ENGINE=InnoDB AUTO_INCREMENT=22 DEFAULT CHARSET=utf8;

 

T_touxiang表SQL:

 

 
  1. DROP TABLE IF EXISTS `t_touxiang`;

  2. CREATE TABLE `t_touxiang` (

  3. `id` int(10) NOT NULL AUTO_INCREMENT,

  4. `image_path` varchar(255) DEFAULT NULL,

  5. `user_id` int(11) DEFAULT NULL,

  6. `old_name` varchar(255) DEFAULT NULL,

  7. PRIMARY KEY (`id`),

  8. KEY `img_user` (`user_id`),

  9. CONSTRAINT `img_user` FOREIGN KEY (`user_id`) REFERENCES `t_user` (`id`)

  10. ) ENGINE=InnoDB AUTO_INCREMENT=6 DEFAULT CHARSET=utf8;

 

首先,写一个UploadServlet.java,用来处理图片文件的上传,并将图片路径,图片名称等信息存放到t_touxiang数据表中,代码如下:

 

 
  1. @WebServlet("/UploadServlet.do")

  2. public class UploadServlet extends HttpServlet {

  3. private static final long serialVersionUID = 1L;

  4.  
  5. protected void service(HttpServletRequest request, HttpServletResponse response)

  6. throws ServletException, IOException {

  7. // 判断上传表单是否为multipart/form-data类型

  8. HttpSession session = request.getSession();

  9. User user = (User) session.getAttribute("user"); // 在登录时将 User 对象放入了 会话

  10. // 中

  11.  
  12. if (ServletFileUpload.isMultipartContent(request)) {

  13.  
  14. try {

  15. // 1. 创建DiskFileItemFactory对象,设置缓冲区大小和临时文件目录

  16. DiskFileItemFactory factory = new DiskFileItemFactory();

  17. // System.out.println(System.getProperty("java.io.tmpdir"));//默认临时文件夹

  18.  
  19. // 2. 创建ServletFileUpload对象,并设置上传文件的大小限制。

  20. ServletFileUpload sfu = new ServletFileUpload(factory);

  21. sfu.setSizeMax(10 * 1024 * 1024);// 以byte为单位 不能超过10M 1024byte =

  22. // 1kb 1024kb=1M 1024M = 1G

  23. sfu.setHeaderEncoding("utf-8");

  24.  
  25. // 3.

  26. // 调用ServletFileUpload.parseRequest方法解析request对象,得到一个保存了所有上传内容的List对象。

  27. @SuppressWarnings("unchecked")

  28. List<FileItem> fileItemList = sfu.parseRequest(request);

  29. Iterator<FileItem> fileItems = fileItemList.iterator();

  30.  
  31. // 4. 遍历list,每迭代一个FileItem对象,调用其isFormField方法判断是否是上传文件

  32. while (fileItems.hasNext()) {

  33. FileItem fileItem = fileItems.next();

  34. // 普通表单元素

  35. if (fileItem.isFormField()) {

  36. String name = fileItem.getFieldName();// name属性值

  37. String value = fileItem.getString("utf-8");// name对应的value值

  38.  
  39. System.out.println(name + " = " + value);

  40. }

  41. // <input type="file">的上传文件的元素

  42. else {

  43. String fileName = fileItem.getName();// 文件名称

  44. System.out.println("原文件名:" + fileName);// Koala.jpg

  45.  
  46. String suffix = fileName.substring(fileName.lastIndexOf('.'));

  47. System.out.println("扩展名:" + suffix);// .jpg

  48.  
  49. // 新文件名(唯一)

  50. String newFileName = new Date().getTime() + suffix;

  51. System.out.println("新文件名:" + newFileName);// image\1478509873038.jpg

  52.  
  53. // 5. 调用FileItem的write()方法,写入文件

  54. File file = new File("D:/lindaProjects/mySpace/wendao/WebContent/touxiang/" + newFileName);

  55. System.out.println(file.getAbsolutePath());

  56. fileItem.write(file);

  57.  
  58. // 6. 调用FileItem的delete()方法,删除临时文件

  59. fileItem.delete();

  60.  
  61. /*

  62. * 存储到数据库时注意 1.保存源文件名称 Koala.jpg 2.保存相对路径

  63. * image/1478509873038.jpg

  64. *

  65. */

  66. if (user != null) {

  67. int myid = user.getId();

  68. String SQL = "INSERT INTO t_touxiang(image_path,user_id,old_name)VALUES(?,?,?)";

  69. int rows = JdbcHelper.insert(SQL, false, "touxiang/" + newFileName, myid, fileName);

  70. if (rows > 0) {

  71. session.setAttribute("image_name", fileName);

  72. session.setAttribute("image_path", "touxiang/" + newFileName);

  73. response.sendRedirect(request.getContextPath() + "/upImage.html");

  74. } else {

  75.  
  76. }

  77.  
  78. } else {

  79. session.setAttribute("loginFail", "请登录");

  80. response.sendRedirect(request.getContextPath() + "/login.html");

  81. }

  82.  
  83. }

  84. }

  85.  
  86. } catch (FileUploadException e) {

  87. e.printStackTrace();

  88. } catch (Exception e) {

  89. e.printStackTrace();

  90. }

  91.  
  92. }

  93. }

  94. }

 

在完成图片上传并写入数据库的同时,将图片路径通过session的方式发送到HTML界面

 

 

 
  1. <!DOCTYPE html>

  2.  
  3. <html>

  4.  
  5. <head>

  6.  
  7. <meta charset="UTF-8">

  8.  
  9. <title>更换头像</title>

  10.  
  11. </head>

  12.  
  13. <body>

  14.  
  15. <formaction="UploadServlet.do" method="post"enctype="multipart/form-data">

  16.  
  17. 本地目录:<inputtype="file" name="uploadFile">

  18.  
  19. <img src="${image_path}" width="200" height="200">

  20.  
  21. <inputtype="submit" value="上传头像"/>

  22.  
  23. </form>

  24.  
  25. </body>

  26.  
  27. </html>

 

至此,图片上传数据库和本地服务器已经实现,那么如何在HTML界面显示出个人信息以及上传的头像呢?

 

 

首先定义一个PersonServlet类,用来读取数据库的内容,并发送到HTML界面。

代码如下:

 
  1. @WebServlet("/persons.do")

  2. public class PersonServlet extends HttpServlet {

  3.  
  4. private static final long serialVersionUID = -800352785988546254L;

  5.  
  6. protected void service(HttpServletRequest request, HttpServletResponse response)

  7. throws ServletException, IOException {

  8. // 判断上传表单是否为multipart/form-data类型

  9. Touxiang tx=null;

  10.  
  11. HttpSession session = request.getSession();

  12. User user = (User) session.getAttribute("user"); // 在登录时将 User 对象放入了 会话

  13. if(user!=null){

  14. int myid=user.getId();

  15. String SQL="SELECT id,image_path,old_name FROM t_touxiang WHERE user_id=?";

  16. ResultSet rs=JdbcHelper.query(SQL,myid);

  17. String uSQL="SELECT username,password FROM t_user WHERE id=?";

  18. ResultSet urs=JdbcHelper.query(uSQL,myid);

  19. System.out.println( "我的个人id是: " + myid);

  20. final List<Touxiang> touxiang=new ArrayList<>();

  21. try {

  22. if(rs.next())

  23. {

  24. tx=new Touxiang();

  25. tx.setId(rs.getInt(1));

  26. tx.setImage_path(rs.getString(2));

  27. tx.setOld_name(rs.getString(3));

  28. touxiang.add(tx);

  29. }

  30. if(urs.next()){

  31. user.setUsername(urs.getString(1));

  32. user.setPassword(urs.getString(2));

  33. user.setTouxiang(touxiang);

  34. }

  35.  
  36. } catch (SQLException e) {

  37. // TODO Auto-generated catch block

  38. e.printStackTrace();

  39. }

  40.  
  41. session.setAttribute("user", user);

  42. System.out.println( "我的id: " + myid);

  43. response.sendRedirect( request.getContextPath() + "/person.html");

  44. }

  45. }

  46. }

  47.  

 

在HTML界面接收信息,并显示出来,代码如下:

 

 
  1. <div>

  2. <form action="UploadServlet.do" method="post" enctype="multipart/form-data">

  3. <div><a href="$path/upImage.html">更换头像</a></div>

  4.  
  5. #foreach( $ut in $user.getTouxiang() )

  6. <img src=" $ut.getImage_path()" width="200" height="200">

  7. #end

  8. <div>我的头像:</div>

  9. <div>我的姓名:$user.getUsername()</div>

  10. <div><a href="$path/myAnswer.do">我的解答</a></div>

  11. <div><a href="$path/myQuestion.do">我的提问</a></div>

  12. </form>

  13. </div>

  14. <div>

  15. <form action="UploadServlet.do" method="post" enctype="multipart/form-data">

  16. <div><a href="$path/upImage.html">更换头像</a></div>

  17.  
  18. #foreach( $ut in $user.getTouxiang() )

  19. <img src=" $ut.getImage_path()" width="200" height="200">

  20. #end

  21. <div>我的头像:</div>

  22. <div>我的姓名:$user.getUsername()</div>

  23. <div><a href="$path/myAnswer.do">我的解答</a></div>

  24. <div><a href="$path/myQuestion.do">我的提问</a></div>

  25. </form>

  26. </div>

 

至此,一个基于Java的头像上传服务器,路径存储在MySQL,并在HTML界面读取出来的功能就基本实现了。头像上传之前进行处理等操作,可以选择一些插件来完成。这里只是简单的实现了基本功能。

 

 

补充

对于图片上传,这里只是简单的用Servlet实现了一下最基本的功能,仅提供思路。如果使用spring等框架,他都对图片上传做了很好的封装,应该更加容易。

后台实现图片上传应该来说比较容易,但是比较头疼的是图片上传原生的按钮丑出天际,这里推荐俩实用的上传控件,应该算比较好看。

 

1,H5实现的图片上传,可多张上传,可点击可拖拽上传,大概是这个样子:

Java实现图片上传到服务器,并把上传的图片读取出来

基本的使用介绍和下载地址:http://blog.csdn.net/weixin_36380516/article/details/70352689

 

2,jQuery图像裁剪插件,大概长这样

Java实现图片上传到服务器,并把上传的图片读取出来

 

不仅提供上传,还有裁剪等功能,UI做的也美,

 

https://blog.csdn.net/weixin_36380516/article/details/58594664