网页设计大赛之将本地图片存放至数据库中并再次显示

所用软件eclipse;后台jdbc框架,获取选取图片的地址并将图片存放到指定位置,并将地址存放至数据库

数据库:mysql

表结构:

 DButil.java

package com.imooc.db;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class DButil {

    private final static String url = "jdbc:mysql://localhost:3306/webbs";
    private final static String user = "root";
    private final static String pw = "root";
    
    static{
        try {
            Class.forName("com.mysql.jdbc.Driver");
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }
    
    public Connection getConn() throws SQLException{
        return DriverManager.getConnection(url,user,pw);
    }
    
    public void close(Connection conn,PreparedStatement pst,ResultSet rs){
        
        try {
            if(conn != null){
                conn.close();
            }
            if(pst != null){
                pst.close();
            }
            if(rs != null){
                rs.close();
            }
            
        } catch (SQLException e) {
            e.printStackTrace();
        }
    
    }

}

Picture.java

package com.picture.Bean;

public class Picture {
private int id;
private String name;
private String picturepath;
public int getId() {
    return id;
}
public void setId(int id) {
    this.id = id;
}
public String getName() {
    return name;
}
public void setName(String name) {
    this.name = name;
}
public String getPicturepath() {
    return picturepath;
}
public void setPicturepath(String picturepath) {
    this.picturepath = picturepath;
}

}

Dao.java

package com.picture.dao;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import com.imooc.db.DButil;
import com.picture.Bean.Picture;


public class Dao extends DButil{
    Connection conn=null;
    private PreparedStatement ps;
    public void add(Picture picture){
        
        try {
            conn = super.getConn();
            String sql="insert into picture_2(name,picturepath)"+" values (?,?)" ;
            ps=conn.prepareStatement(sql);
            ps.setString(1,picture.getName());
            ps.setString(2,picture.getPicturepath());
              ps.execute();
        } catch (SQLException e) {
            e.printStackTrace();
        }
      
    }

    
    
}

SDao.java

package com.picture.dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import com.imooc.db.DButil;
import com.picture.Bean.Picture;



public class SDao extends DButil{
    Connection conn=null;
    private PreparedStatement ps;
public List<Picture> getpicture(String name) {
        
        Connection conn  = null;
        PreparedStatement pst = null;
        ResultSet rs = null;  
           
        List<Picture> list = new ArrayList<Picture>(); 
        
        try {
            conn = super.getConn();  
            pst = conn.prepareStatement("select name,picturepath from picture_2 where name='"+name+"'");
            rs = pst.executeQuery();
            while(rs.next()){
                    Picture users = new Picture();
                    users.setName(rs.getString(1));
                    users.setPicturepath(rs.getString(2));
                list.add(users);
                 
            }  
        } catch (SQLException e) {
            e.printStackTrace();
        }finally{
            super.close(conn, pst, rs);
        } 
        return list;
    }
}

downloadServlet.java 根据路径下载显示图片信息至桌面上

package com.picture.servlet;

import java.io.IOException;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.picture.Bean.Picture;
import com.picture.dao.SDao;

public class downloadServlet extends HttpServlet{
    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        this.doPost(request, response);
    }
 
    /**
     * 闲研碎语的所有值查询的方法
     * 将topic1中所有值查询出来
     */
    public void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        request.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charset=utf-8");
        String name = request.getParameter("name");
        System.out.print(name);
        SDao topicListDao = new SDao(); 
        List<Picture> meAndAllFriendTopic = topicListDao.getpicture(name);
        
        request.setAttribute("meAndAllFriendTopic", meAndAllFriendTopic);
        
        request.getRequestDispatcher("/xianshi.jsp").forward(request, response);
        
             
    }
}

upServlet.java 上传图片至目标文件夹并将地址保存至数据库

package com.picture.servlet;
import com.picture.Bean.Picture;
import com.picture.dao.Dao;
 
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Calendar;
import java.util.List;
 
import javax.servlet.ServletException;
import javax.servlet.ServletInputStream;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
 
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
 
/**
 * Servlet implementation class upServlet
 */
//@WebServlet("/upServlet")
public class upServlet extends HttpServlet {
 private static final long serialVersionUID = 1L;
   
   
 protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
  
 }
 protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
  //通知客户端以utf-8编码进行解析
        
    response.setContentType("text/html;charset=utf-8");
    //数据库以UTF-8编码解析数据
    request.setCharacterEncoding("UTF-8");
    
    String name=null;
   
       Picture picture=new Picture();
       Dao dao=new Dao();
    //判断请求是否为multipar请求
    if(!ServletFileUpload.isMultipartContent(request))
    {
     throw new RuntimeException("当前请求不支持文件上传");
    }
    //为基于磁盘的文件项创建一个FileItem工厂
    DiskFileItemFactory factory = new DiskFileItemFactory();
    //设置临时文件的边界值,大于该值时,上传文件会先保存在临时文件中,否则,上传文件将直接写入到内存
    //单位:字节,设置边界值1M,一字节=1024M;
    factory.setSizeThreshold(1024*1024*1);
    //设置文件临时储存
    String temppath=this.getServletContext().getRealPath("/temp");
    File temp=new File(temppath);
    factory.setRepository(temp);
    //创建一个新的文件上传处理程序
    ServletFileUpload upload = new ServletFileUpload(factory);
    //设置每一个item的头部字符编码,其可以解决文件名中文乱码问题;
    upload.setHeaderEncoding("UTF-8");
    //设置单个文件的最大边界值(这里是2M)
    upload.setFileSizeMax(1024*1024*2);
    //设置一次上传所有文件总和的最大值(对上传多个文件起作用,这里最大为5M)
    upload.setSizeMax(1024*1024*5);
    //解析请求,获取所有的item
    try {
    //
     //调用ServletFileUpload.parseRequest方法解析request对象,
     //得到一个保存了所有上传内容的List对象。
    List <FileItem> items = upload.parseRequest(request);
    //遍历
    for(FileItem item:items){
    //若item为普通表单项
     if(item.isFormField()){
     //获取表单中属性名称
     String fieldName = item.getFieldName();
     if(fieldName.equals("name")){
     //获取表单属性的值
      name=item.getString("UTF-8");
     }
     System.out.println(fieldName+"="+name);
    //若 item为文件表单项
     }else{
     //获取文件大小
     long size=item.getSize();
     //获取文件类型
     String contentType = item.getContentType();
     //获取上传文件原始名字
     String fileName = item.getName();
     System.out.println("文件大小:"+size);
     System.out.println("文件的类型:"+contentType);
     //System.out.println("文件的名称:"+fileName);
        //获取文件名,处理获取到的上传文件的文件名的路径部分,只保留文件名部分
     if(fileName.contains("\"))
              {
                  //如果包含则截取字符串
      fileName=fileName.substring(fileName.lastIndexOf("\")+1);
              }
     //设置文件名,因为同名的文件会覆盖,所以要修饰文件名,设置毫秒+文件名
     fileName=System.currentTimeMillis()+fileName;
     System.out.println("文件的名称:"+fileName);
     //获取输入流,其实有上传文件的内容
     InputStream inputStream = item.getInputStream();
     
     //String parent=this.getServletContext().getRealPath("./images");
     String path="C:\Users\HP\eclipse-workspace\photo1\WebContent\image";
     File dirFile=new File(path);
     if(!dirFile.exists()){
      //创建多级目录mkdirs()
      dirFile.mkdir();
     }
     //创建目录文件,将来用于保存上传文件
     File file = new File(path, fileName);
     //创建文件输出流
     OutputStream os=new FileOutputStream(file); 
     //把输入流中的数据写入到输出流
     int len=0;
     byte[] buf=new byte[1024];
     while((len=inputStream.read(buf))!=-1){
      os.write(buf, 0, len);
     }
                   //图片上传到之后的路径
     path="C:\Users\HP\eclipse-workspace\photo1\WebContent\image"+"\"+fileName;
     String path1="image"+"\"+fileName;
     picture.setName(name);
     picture.setPicturepath(path1);
     System.out.println(picture.getName()+"----"+picture.getPicturepath());
                   //调用Dao中的add()方法
     dao.add(picture);
     os.close();
     inputStream.close();
     //删除临时文件
     item.delete();
     }
    } 
     
    } catch (FileUploadException e) {
     
     e.printStackTrace();
    }
   }
}

 pictureup.jsp

<%@ page language="java" contentType="text/html; charset=utf-8"
    pageEncoding="utf-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Insert title here</title>
</head>
<body>
    <form action="${pageContext.request.contextPath}/uppicture" method="post"  enctype="multipart/form-data" >
     昵称:<input type="text" name="name"><br>
            <div>
                  <img src="${image_path}" width="200" height="200">
             </div>
              头像:<input type="file" name="uploadFile"> 
        <input type="submit" value="上传头像"/>
   </form>
</body>

</html>

xianshi.jsp 用于图片显示的界面

<%@ page language="java" contentType="text/html; charset=utf-8"
    pageEncoding="utf-8"%>
    <%@ taglib uri = "http://java.sun.com/jsp/jstl/core" prefix = "c"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Insert title here</title>
</head>
<body>
    <form action="${pageContext.request.contextPath}/xianshi" method="post">
     昵称:<input type="text" name="name"><br>
              
        <input type="submit" value="下载头像"/>
   </form>
   <c:forEach items="${requestScope.meAndAllFriendTopic}" var="item" >
   <div>
   <a>${item.name}</a>
                  <img src="${item.picturepath}" width="100" height="100">
             </div>
   </c:forEach>
</body>

</html>

web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" id="WebApp_ID" version="3.1">
  <display-name>picture-up</display-name>
  <servlet>
          <servlet-name>uppicture</servlet-name>
          <servlet-class>com.picture.servlet.upServlet</servlet-class>
  </servlet>
  <servlet>
          <servlet-name>xianshi</servlet-name>
          <servlet-class>com.picture.servlet.downloadServlet</servlet-class>
  </servlet>
  
  
  <servlet-mapping>
          <servlet-name>xianshi</servlet-name>
          <url-pattern>/xianshi</url-pattern>
  </servlet-mapping>
  <servlet-mapping>
          <servlet-name>uppicture</servlet-name>
          <url-pattern>/uppicture</url-pattern>
  </servlet-mapping>
</web-app>

运行截图:

由于eclipse自身的延迟原因在下载图片时必须要刷新images文件夹

用途:可以作为更改头像使用

原文地址:https://www.cnblogs.com/jinseliunian/p/12009511.html