当前位置: 移动技术网 > IT编程>开发语言>Java > Java实现图片上传到服务器并把上传的图片读取出来

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

2019年07月22日  | 移动技术网IT编程  | 我要评论

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

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

实现的思路:

工具: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>

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

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

代码如下:

@webservlet("/persons.do") 
public class personservlet extends httpservlet { 
  private static final long serialversionuid = -800352785988546254l; 
  protected void service(httpservletrequest request, httpservletresponse response) 
    throws servletexception, ioexception { 
  // 判断上传表单是否为multipart/form-data类型 
  touxiang tx=null; 
  httpsession session = request.getsession(); 
  user user = (user) session.getattribute("user"); // 在登录时将 user 对象放入了 会话 
  if(user!=null){ 
    int myid=user.getid(); 
    string sql="select id,image_path,old_name from t_touxiang where user_id=?"; 
    resultset rs=jdbchelper.query(sql,myid); 
    string usql="select username,password from t_user where id=?"; 
    resultset urs=jdbchelper.query(usql,myid); 
    system.out.println( "我的个人id是: " + myid); 
    final list<touxiang> touxiang=new arraylist<>(); 
    try { 
    if(rs.next()) 
    { 
      tx=new touxiang(); 
      tx.setid(rs.getint(1)); 
      tx.setimage_path(rs.getstring(2)); 
      tx.setold_name(rs.getstring(3)); 
      touxiang.add(tx); 
    } 
    if(urs.next()){ 
      user.setusername(urs.getstring(1)); 
      user.setpassword(urs.getstring(2)); 
      user.settouxiang(touxiang); 
    } 
    } catch (sqlexception e) { 
    // todo auto-generated catch block 
    e.printstacktrace(); 
    } 
    session.setattribute("user", user); 
    system.out.println( "我的id: " + myid); 
    response.sendredirect( request.getcontextpath() + "/person.html"); 
  } 
  } 
} 

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

<span style="white-space:pre"> </span><div> 
  <form action="uploadservlet.do" method="post" enctype="multipart/form-data"> 
       <div><a href="$path/upimage.html" rel="external nofollow" >更换头像</a></div> 
      #foreach( $ut in $user.gettouxiang() ) 
       <img src=" $ut.getimage_path()" width="200" height="200"> 
       #end 
       <div>我的头像:</div> 
       <div>我的姓名:$user.getusername()</div> 
       <div><a href="$path/myanswer.do" rel="external nofollow" >我的解答</a></div> 
    <div><a href="$path/myquestion.do" rel="external nofollow" >我的提问</a></div> 
  <span style="white-space:pre">  </span> </form> 
  </div> 

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

以上所述是小编给大家介绍的java实现图片上传到服务器并把上传的图片读取出来,希望对大家有所帮助

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网