javaweb 学习第4篇 - JavaBean的使用,上传图片 - 2018.11.2

通过JavaBean创建表结构(要有存储图片字段)。通过Jsp界面录入数据,具备上传图片功能(单张图片即可)。提供一个列表界面、用分页及表格形式显示这些数据,在列表界面点击某条记录,跳转到详细信息界面,要能把上传的图片显示出来


1.创建工程

 

  1. 创建upfile.jsp

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

<%@ page import = "cn.java.UpFile" %>

<%@ page import = "com.jspsmart.upload.SmartUpload" %>

 

<jsp:useBean id="upFile" class="cn.java.UpFile" 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>

 

 

    <p>选择要上传的文件:</p><br/>

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

    <input type=FILE name="image" size="45"/><br/>

    <input type="submit" name="g" value="提交"/>

   </form>

  

   <!-- 使用session对象获取表单信息    先使用request对象获取表单信息,然后使用session对象的setAttribute()方法,将获取到的信息写入session,需要使用时,再通过getAttribute()方法读取表单信息 -->

  

    <!-- 使用如上事例处理表单时,使用jsp的useBean指令的setProperty 指令 ,使用 property="*" 

               会将前端 请求参数 (此处为表单传过来的表单数据)按照javabean的属性名对应,注入到声明的实例对象stuInfo中,如果属性名

               于前端表单的属性名不对应,则跳过该属性名数据的注入。

          ---------------------

               作者:suyu_yuan

               来源:****

               原文:https://blog.****.net/suyu_yuan/article/details/50936497

               版权声明:本文为博主原创文章,转载请附上博文链接!

              

              

         表单中enctype="multipart/form-data"的意思,是设置表单的MIME编码。默认情况,这个编码格式是application/x-www-form-urlencoded,不能用于文件上传;

        只有使用了multipart/form-data,才能完整的传递文件数据,进行下面的操作.enctype="multipart/form-data"是上传二进制数据; form里面的input的值以2进制的方式传过去。

        form里面的input的值以2进制的方式传过去,

        所以request就得不到值了。也就是说加了这段代码,用request就会传递不成功,取表单值加入数据库时,用到下面的:

       

        SmartUpload su = new SmartUpload();//新建一个SmartUpload对象

       

        su.getRequest().getParameterValues();取数组值

       

        su.getRequest().getParameter( );取单个参数单个值     

       

 

 

       request.setCharacterEncoding("UTF-8");

       SmartUpload su = new SmartUpload();//新建一个SmartUpload对象

       String title = su.getRequest().getParameter("title");

       System.out.println("888title:"+title);

       String person = su.getRequest().getParameter("person");

       System.out.println("888person:"+person);

        session.setAttribute("title",title);

       session.setAttribute("person",person);

 

   -->

   <%

       upFile.setRequest(request);

       upFile.setSession(session);

    %>

    

 

 

    <jsp:getProperty name="upFile" property="upFileMessage"/>

    <p>如果上传的是图像文件,可单击超链接查看图像:</p><br/>

    <a href="show.jsp">查看列表</a>

  </body>

</html>

 

  1. 创建UpFile.java文件

package cn.java;

import java.io.File;

import java.io.FileOutputStream;

import java.io.InputStream;

import java.io.RandomAccessFile;

import java.io.Serializable;

import java.nio.file.Path;

 

import javax.servlet.*;

import javax.servlet.http.*;

import javax.servlet.annotation.*;

 

 

public class UpFile extends HttpServlet implements Serializable{

       HttpServletRequest request;

       HttpSession session;

       String upFileMessage = "";

       int count = 0;

       String title;

       String file = null;

      

       public void setRequest(HttpServletRequest request)

       {

              this.request = request;

       }

      

       public HttpSession getSession()

       {

              return session;

       }

      

       public void setSession(HttpSession session)

       {

              this.session = session;

       }

      

       public String getUpFileMessage()

       {

              String fileName = null;

              String writer = null;

              String title = null;

              String tempfile = null;

              try

              {

                     String tempFileName = (String)session.getId();

                    

                     //title = (String)session.getAttribute("title");

                     //System.out.println("title的值为:"+title);

                     //writer = (String)session.getAttribute("person");

                     //System.out.println("writer的值为:"+writer);

                     //System.out.print(tempFileName);

                     //String path = this.getServletContext().getRealPath("/WEB-INF");

                     //File f1 = new File(path,tempFileName);

                     File f1=new File("H://vPhoto",tempFileName);

                     FileOutputStream o = new FileOutputStream(f1);

                     InputStream in = request.getInputStream();

                     byte b[] = new byte[10000];

                     int n;

                     while((n = in.read(b)) != -1)

                     {

                            o.write(b,0,n);

                     }

                     o.close();

                     in.close();

                     RandomAccessFile random = new RandomAccessFile(f1,"r");

                     int second = 1; ///读取f1的第2行,析取出长传文件的名字

                     String secondLine = null;

                     while(second <= 2)

                     {

                            secondLine = random.readLine();

                            System.out.println("secondLine的值为:"+secondLine);

                            second++;

                     }

                    

                     //获得 第2行中目录符号‘/’最后出现的位置

                     System.out.println("secpmd:"+secondLine);

                     int position = secondLine.lastIndexOf("//");

                    

                     if(position >= 0)

                     {

                    

                            //客户上传的文件的名字是:

                            fileName = secondLine.substring(position+1,secondLine.length()-1);

                            System.out.println("XXXXXXXX1:"+fileName);

                     }

                     else

                     {

                            fileName = secondLine.substring(position+1,secondLine.length()-1);

                            position = secondLine.lastIndexOf("=");

                            fileName = secondLine.substring(position+2,secondLine.length()-1);

                            System.out.println("XXXXXXXX2:"+fileName);

                     }

                     //String path = "d://long";

                     //fileName = path + "//" + fileName;

                     byte cc[] = fileName.getBytes("ISO-8859-1");

                     fileName = new String(cc);

                     //tempfile = fileName + "|" + title + "|" + writer;

                     tempfile = fileName;

                     System.out.println("tempfile:"+tempfile);

                     //session.setAttribute("Path", "/demo/");

                     count++;//图片数量+1            

                     session.setAttribute(String.valueOf(count), tempfile); //show.jsp页面使用

                     random.seek(0);//再定位到文件f1的开头

                     //获取第4行回车符号的位置

                     long forthEndPosition = 0;

                     int forth = 1;

                     while((n = random.read())!=-1 && (forth <= 4))

                     {

                            if(n == '\n')

                            {

                                   forthEndPosition = random.getFilePointer();

                                   System.out.println(forthEndPosition);

                                   forth++;

                            }

                     }

                    

                     //根据客户上传文件的名字,将该文件保存到磁盘上

                     //String path2 = this.getServletContext().getRealPath("/WEB-INF");

                     //File f2 = new File(path2,fileName);

                     File f2=new File("H://vPhoto",fileName);

                     RandomAccessFile random2 = new RandomAccessFile(f2,"rw");

                    

                      //确定出文件f1中包含客户上传得文件的内容的最后位置,即倒数第6行

                     random.seek(random.length());

                     long endPosition = random.getFilePointer();

                     long mark = endPosition;

                    

                     int j = 1;

                     while((mark >= 0) && (j <= 6))

                     {

                            mark--;

                            random.seek(mark);

                            n = random.readByte();

                           

                            if(n == '\n')

                            {

                                   endPosition = random.getFilePointer();

                                   j++;

                            }

                           

                     }

                    

                     //将random流指向文件f1的第4行结束的位置

                     random.seek(forthEndPosition);

                     long startPoint = random.getFilePointer();

                    

                     //从f1读出客户上传得文件存入f2

                     //(读取从第四行到倒数第六行之间的内容)

                     while(startPoint < endPosition-1)

                     {

                            n = random.readByte();

                            random2.write(n);

                            startPoint = random.getFilePointer();

                     }

                    

                     random2.close();

                     random.close();

                    

                     f1.delete();

                     upFileMessage = fileName + " successfully UpLoad";

                     return upFileMessage;

              }

              catch(Exception exp)

              {

                     if(fileName != null)

                     {

                            upFileMessage = fileName + " Fail to upload";

                            return upFileMessage;

                     }

                     else

                     {

                            upFileMessage = "error:file (" + fileName + ") is null";

                            return upFileMessage;

                     }

              }

       }

      

       public void setUpFileMessage(String upFileMessage)

       {

              this.upFileMessage = upFileMessage;

       }

      

       public HttpServletRequest getRequest()

       {

              return request;

       }

}

 

 

  1. 创建show.jsp

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

<jsp:useBean id="upFile" class="cn.java.UpFile" scope="session"/>

 

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

<html>

  <head>

   

   

    <title>SHOW</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>

    <%

    java.util.Enumeration e  = session.getAttributeNames();

    String path = (String)session.getAttribute("Path");

    //String pic = path + fileName;

    //out.print(pic);

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

    %>

    <center>

    <a>商城</a>

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

       <%

           int i = 0;

           String Path ="/demo/";

           String stri = String.valueOf(i);

           String strinf[] = new String[100];

           //String temp;

           String pic;

          

           while(e.hasMoreElements())

            {

                strinf[i] = String.valueOf(session.getAttribute(e.nextElement().toString()));

                i++;

            }

          

           String pathToShow = "show0.jsp";

          

           out.println("<tr><td>序号</td><td width=\"100\">图片</td><td>主题</td><td>提交者</td></tr>");

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

            {

                pic = Path + strinf[j];

                out.println("<tr><td >"+(j+1)+"</td><td width=\"100\" height=\"100\"><img  width=\"100%\" height=\"100%\"  src="+pic+"></td><td>");

                    out.println("<a href="+ pathToShow + "?fileName=" + strinf[j] + ">"+strinf[j]+"</a>");

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

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

            }

        %>

   </table>

    </center>

   

  </body>

</html>

 

  1. 创建show0.jsp

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

<jsp:useBean id="upFile" class="cn.java.UpFile" 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>

       <%

    //String fileName = (String)session.getAttribute("Name");

    //String path = (String)session.getAttribute("Path");

    //String pic = path + fileName;

    //out.print(pic);

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

   

    //String fileName = request.getQueryString();

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

     String path ="/demo/";

    String pic = path + fileName;

    out.print(pic);

    out.print("<img src="+pic+">");

    %>

  </body>

</html>

 

测试:

javaweb 学习第4篇 - JavaBean的使用,上传图片 - 2018.11.2

javaweb 学习第4篇 - JavaBean的使用,上传图片 - 2018.11.2

 

javaweb 学习第4篇 - JavaBean的使用,上传图片 - 2018.11.2

 

 


在实验过程中我遇到了只能上传图片而不能上传图片其他内容的问题

通过百度的方式,我认识到要上传文件要使用smartupload这类的组件,没有解决了这个问题。

只能在下一个作业使用此类组件