javaweb学习第5篇 - 上传图片路径 - 2018.11.6

    xiaoxiao2022-07-04  120

    结合实验6进行改进,把图片存储到数据库,存放图片的路径,存放的路径只能是相对路径,不能带有盘符


    1.创建FileUpLoad..java文件

    package myServlet;

     

    import java.io.*;

    import javax.servlet.*;

    import javax.servlet.http.*;

    import org.apache.commons.fileupload.*;

    import java.util.*;

    import org.apache.commons.fileupload.*;

    import org.apache.commons.io.*;

    import JDBC.UseJdbc;

     

    public class UploadServlet extends HttpServlet

    {

           public void doPost(HttpServletRequest request,HttpServletResponse response) throws ServletException,IOException

           {           

                  String path[] = new String[2];

                  String author,comefrom;

                  path[0] = "";

                  path[1] = "";

                  response.setContentType("text/html;charset=gb2312");

                  PrintWriter out = response.getWriter();

                                            

                  //设置保存上传文件的目录

                  String uploadDir = getServletContext().getRealPath("/upload");

                  if (uploadDir == null)

                  {

                         out.println("无法访问存储目录!");

                         return;

                  }

                  File fUploadDir = new File(uploadDir);

                  if(!fUploadDir.exists())

                  {

                         if(!fUploadDir.mkdir())

                         {

                                out.println("无法创建存储目录!");

                                return;

                         }

                  }

       

                  if (!DiskFileUpload.isMultipartContent(request))

                  {

                         out.println("只能处理multipart/form-data类型的数据!");

                         return ;

                  }

                    

                  DiskFileUpload fu = new DiskFileUpload();

                  //最多上传200M数据

                  fu.setSizeMax(1024 * 1024 * 200);

                  //超过1M的字段数据采用临时文件缓存

                  fu.setSizeThreshold(1024 * 1024);

                  //采用默认的临时文件存储位置

                  //fu.setRepositoryPath(...);

                  //设置上传的普通字段的名称和文件字段的文件名所采用的字符集编码

                  fu.setHeaderEncoding("gb2312");

                 

                  //得到所有表单字段对象的集合

                  List fileItems = null;

                  try

                  {

                         fileItems = fu.parseRequest(request);

                  }

                  catch (FileUploadException e)

                  {

                         out.println("解析数据时出现如下问题:");

                         e.printStackTrace(out);

                         return;

                  }

                 

                  //处理每个表单字段

                  Iterator i = fileItems.iterator();

                  int j = 0;

                  while (i.hasNext())

                  {

                         FileItem fi = (FileItem) i.next();

                         if (fi.isFormField())

                         {

                                String content = fi.getString("GB2312");

                                String fieldName = fi.getFieldName();

                                request.setAttribute(fieldName,content);

                         }

                         else

                         {

                                try

                                {

                                       String pathSrc = fi.getName();

                                       /*如果用户没有在FORM表单的文件字段中选择任何文件,

                                       那么忽略对该字段项的处理*/

                                       if(pathSrc.trim().equals(""))

                                       {

                                              continue;

                                       }

                                       int start = pathSrc.lastIndexOf('\\');

                                       String fileName = pathSrc.substring(start + 1);

                                       path[j] = "/ImageToDb_20181106/upload/" + fileName;

                                       j++;

                                       File pathDest = new File(uploadDir, fileName);          

                                       fi.write(pathDest);

                                       String fieldName = fi.getFieldName();

                                       request.setAttribute(fieldName, fileName);

                                      

                                }

                                catch (Exception e)

                                {

                                          out.println("存储文件时出现如下问题:");

                                          e.printStackTrace(out);

                                  

                                          return;

                                }

                                finally  //总是立即删除保存表单字段内容的临时文件

                                {

                                       fi.delete();

                                }

     

                         }

                  }

                 

                  //显示处理结果

                  out.println("用户:" + request.getAttribute("author") + "<br>");

                  out.println("来自:" + request.getAttribute("company") + "<br>");

                 

                  /*将上传的文件名组合成"file1,file2"这种形式显示出来,如果没有上传

                   *任何文件,则显示为"无",如果只上传了第二个文件,显示为"file2"。*/

                  StringBuffer filelist = new StringBuffer();

                  String file1 = (String)request.getAttribute("file1");

                  makeUpList(filelist,file1);

                  String file2 = (String)request.getAttribute("file2");

                  makeUpList(filelist,file2);

                  out.println("成功上传的文件:" +

                         (filelist.length()==0 ? "无" : filelist.toString()));

                 

                  //把信息存储到数据库

                  author = (String)request.getAttribute("author");

                  comefrom = (String)request.getAttribute("company");

                 

                  out.println("path[0]:"+path[0]+",path[1]:"+path[1]+",author:"+author+",comefrom:"+comefrom);

                 

                 

                  UseJdbc myJdbc = new UseJdbc();

                 

                  for(int k = 0; k < path.length; k++)

                  {

                         if(path[k].equals("") == false)

                         {

                                int rs = myJdbc.Insert(path[k], author, comefrom);

                                if(rs < 1)

                                {

                                       out.println("插入数据库失败!!!");

                                }

                                else

                                {

                                       out.println("插入成功!影响行数rs=" + rs);

                                }

                         }

                         else

                         {

                                out.println("path["+k+"]为空");

                         }

                  }

                 

                  String goShowStore = "ShowStore.jsp";

                  out.println("<a href="+ goShowStore +">商城<//a>");

          

                 

                  myJdbc.Close();

                 

          

     

           }

          

           /**

            *将一段字符串追加到一个结果字符串中。如果结果字符串的初始内容不为空,

            *在追加当前这段字符串之前先最加一个逗号(,)。在组合sql语句的查询条件时,

            *经常要用到类似的方法,第一条件前没有"and",而后面的条件前都需要用"and"

            *作连词,如果没有选择第一个条件,第二个条件就变成第一个,依此类推。

            *

            *@param result 要将当前字符串追加进去的结果字符串

            *@param fragment 当前要追加的字符串

            */

           private void makeUpList(StringBuffer result,String fragment)

           {

                  if(fragment != null)

                  {

                         if(result.length() != 0)

                         {

                                result.append(",");

                         }

                         result.append(fragment);

                  }           

           }

          

           public String getPath(String path) throws ServletException

           {

                  //init();

                  return  (String)getServletContext().getRealPath(path);

           }

          

           public void init(ServletConfig config) throws ServletException{

                  //重写了Servlet的init方法后一定要记得调用父类的init方法,否则在service/doGet/doPost方法中使用getServletContext()方法获取ServletContext对象时就会出现java.lang.NullPointerException异常

                  super.init(config);

           }

    }

     

    2.导入jdbc jar'包和FileUpLoad  jar包,导入commons.io包

     

     

    3.创建fileupload.html

    <!DOCTYPE html>

    <html>

    <head>

        <title>upload experiment</title>

        <meta http-equiv="Content-Type" content="text/html; charset=gb2312">

    </head>

    <body>

        <h3>测试文件上传组件的页面</h3>

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

            作者:<input type="text" name="author"><br>

            来自:<input type="text" name="company"><br>

            文件1:<input type="file" name="file1"><br>

            文件2:<input type="file" name="file2"><br>

            <input type="submit" value="上载">

        </form>

    </body>

    </html>

     

     

    创建showImage.jsp

    <%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>

    <jsp:useBean id="uploadServlet" class="myServlet.UploadServlet" scope="session"/>

     

    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">

    <html>

      <head>

       

       

        <title>具体图片</title>

       

        <meta http-equiv="pragma" content="no-cache">

        <meta http-equiv="cache-control" content="no-cache">

        <meta http-equiv="expires" content="0">   

        <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">

        <meta http-equiv="description" content="This is my page">

        <!--

        <link rel="stylesheet" type="text/css" href="styles.css">

        -->

     

      </head>

     

      <body>

        <center>

            <%

                String path = request.getParameter("path");

                //String realPath = uploadServlet.getPath(path);

                String author = request.getParameter("author");

                String comefrom = request.getParameter("comefrom");

                out.print("<img src="+ path +"><br/>");

                out.print("<a>作者:"+author+"</a><br/>");

                out.print("<a>作者:"+comefrom+"</a><br/>");

                //out.println("path="+path);

             %>

        </center>

      </body>

    </html>

     

     

    创建ShowStore.jsp

    <%@page import="java.net.URLEncoder"%>

    <%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>

    <%@ page import="JDBC.UseJdbc"%>

    <%@ page import="java.sql.*"%>

    <jsp:useBean id="uploadServlet" class="myServlet.UploadServlet" scope="session"/>

     

    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">

    <html>

      <head>

       

        <title>商城</title>

       

        <meta http-equiv="pragma" content="no-cache">

        <meta http-equiv="cache-control" content="no-cache">

        <meta http-equiv="expires" content="0">   

        <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">

        <meta http-equiv="description" content="This is my page">

        <!--

        <link rel="stylesheet" type="text/css" href="styles.css">

        -->

     

      </head>

     

      <body>

         <center>

        <a>商城</a>

       <table  border="1" cellspacing="0" cellpadding="0">

           <%        

          

               UseJdbc myJdbc = new UseJdbc();

              

               ResultSet rs = myJdbc.Select();

              

               String pathToShow = "showImage.jsp";

              

               String strinf[][] = new String[100][4];

              

               out.println("<tr><td>序号</td><td width=\"100\">图片</td><td>作者</td><td>来自</td><td>路径</td></tr>");          

               //处理结果

               int j = 0;

               String aa = "1.PNG";

              

               while(rs.next())

               {  

                   strinf[j][0] = String.valueOf(rs.getInt("id"));

                   strinf[j][1] = String.valueOf(rs.getString("path"));

                   strinf[j][2] = String.valueOf(rs.getString("author"));

                   strinf[j][3] = String.valueOf(rs.getString("comefrom"));

                   j++;

               }

              

                for(int i = 0; i < j; i++)

                {

                    //int id = rs.getInt("id");

                    //String path = String.valueOf(rs.getString("path"));

                    //SavePath[j] = String.valueOf(path);

                    //aa = String.valueOf(rs.getString("path"));

                    //String realPath = uploadServlet.getPath(path);

                    //String author = rs.getString("author");

                    //String comefrom = rs.getString("comefrom");

                    out.println("<tr><td >"+strinf[i][0] +"</td><td width=\"100\" height=\"100\"><img  width=\"100%\" height=\"100%\"  src="+strinf[i][1]+"></td><td>"+strinf[i][2]+"</td><td>");

                    out.println("<a href=" + pathToShow + "?path=" + URLEncoder.encode(strinf[i][1]) + "&author=" + URLEncoder.encode(strinf[i][2]) + "&comefrom=" + URLEncoder.encode(strinf[i][3]) + ">" + strinf[i][3] +"</a></td>");

                    out.println("<td>"+strinf[i][1]+"</td>");            

                    out.println("</tr>");

                }

                //"&author=" + author + "&comefrom=" + comefrom + "

                //+ "&author=" + author.toString() + "&comefrom=" + comefrom.toString() +

                myJdbc.Close();

            %>

       </table>

        </center>

      </body>

    </html>

     

    创建useJdbc.java

    package JDBC;

     

    import java.sql.*;

     

    import javax.servlet.http.HttpServlet;

     

    import java.io.*;

     

    public class UseJdbc{

     

           String url;

           String dbUser;

           String dbPassword;

           Connection conn;

           Statement stmt;

           public UseJdbc()

           {

                  try{

                        

                  //PrintWriter out=response.getWriter();

                  //载入JDBC驱动程序

                  Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver").newInstance();

          

                  //定义连接URL、数据用户及密码

                  url = "jdbc:sqlserver://localhost:1433;DatabaseName=Store";       

                  dbUser = "sa";

                  dbPassword = "laotu123";

                 

                  //建立连接

                  conn= DriverManager.getConnection(url,dbUser,dbPassword);

                 

                  //创建Statement对象(声明对象)

                  stmt=conn.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,ResultSet.CONCUR_UPDATABLE);

                 

                  }catch(ClassNotFoundException ex)

                  {

                         //out.println("加载类失败:"+ex.getMessage());

                         ex.printStackTrace();

                        

                  }catch(SQLException ex2)

                  {

                         //PrintWriter out=response.getWriter();

                         //out.println("执行SQL出错:"+ ex2.getMessage());

                         ex2.printStackTrace();

                  }

                  catch(InstantiationException ex3)

                  {

                         ex3.printStackTrace();

                  }

                  catch(IllegalAccessException ex4)

                  {

                         ex4.printStackTrace();

                  }

           }

          

           public ResultSet Select()

           {    

                  try

                  {

                         String sql="select * from ssImageInf";

                        

                         //执行查询或更新数据

                         ResultSet rs = stmt.executeQuery(sql);

                        

                         return rs;

                  }

                  catch(SQLException e)

                  {

                         e.printStackTrace();

                         return null;

                  }    

           }

          

           public int Insert(String path,String author, String comeFrom)

           {

                  try

                  {

                         String sql="insert into ssImageInf(path,author,comefrom) values ( ' " + path + " ' ,  ' " + author + " ' , ' " + comeFrom + " ' )";

                         int rs = stmt.executeUpdate(sql);

                         return rs;

                  }

                  catch(SQLException e)

                  {

                         e.printStackTrace();

                         return -99;

                  }    

           }

          

           public void Close()

           {

                  try

                  {

                         conn.close();

                  }

                  catch(SQLException e)

                  {

                         e.printStackTrace();

                  }

           }

    }

     

    7、创建web.xml文件

    <?xml version="1.0" encoding="UTF-8"?>

     

    <web-app version="3.0"

        xmlns="http://java.sun.com/xml/ns/javaee"

        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

        xsi:schemaLocation="http://java.sun.com/xml/ns/javaee

        http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd">

      <display-name></display-name>

      <welcome-file-list>

          <welcome-file>fileUpload.html</welcome-file>

      </welcome-file-list>

     

      <servlet>

          <servlet-name>UploadServlet</servlet-name>

          <servlet-class>myServlet.UploadServlet</servlet-class>

      </servlet>  

      <servlet-mapping>

          <servlet-name>UploadServlet</servlet-name>

          <url-pattern>/UploadServlet</url-pattern>

      </servlet-mapping> 

     

    </web-app>

    测试:

     

    最新回复(0)