基于JSP+Servlet+JavaBean的图片或文件上传

基于JSP+Servlet+JavaBean的图片或文件上传

一、概述

现在不管是博客论坛还是企业办公,都离不开资源的共享。通过文件上传的方式,与大家同分享,从而达到大众间广泛的沟通和交流,我们既可以从中获得更多的知识和经验,也能通过他人的反馈达到自我改进和提升的目的。

下面我就为大家介绍 web项目中的这一上传功能,那么文件是如何从本地发送到服务器的呢?大家可以在在线视频课程进修学习《基于JSP+Servlet+JavaBean的人力资源管理系统开发》中第22课-项目开发-其它功能完善-图片上传,同时共享资料并提供相关答疑

课程观看地址:http://www.xuetuwuyou.com/course/53

讲师:蒋子厚http://www.xuetuwuyou.com/user/1984。

课程出自学途无忧网:http://www.xuetuwuyou.com

二、Servlet实现文件上传,需要添加第三方提供的jar

1) commons-fileupload-1.2.2-bin.zip  

2) commons-io-2.3-bin.zip 

首先,我们创建一个新的web工程,在工程的WebRoot目录下新建一个upload文件夹,这样当我们将该工程部署到服务器上时,服务器便也生成个upload文件夹,用来存放上传的资源。

三:文件上传的JSP文件要求和例子

表单提交方式必须是POST方式,

编码类型:enctype="multipart/form-data",

默认是 application/x-www-form-urlencoded

比如:<formaction="FileUpLoad"enctype="multipart/form-data"method="post">

然后,在WebRoot目录下新建一个jsp文件,主要实现的作用就是选择上传的文件,提交至servlet来进行处理详细代码如下:一个form将文件信息通过post方式传送到指定的servlet 

JSP代码如下:

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

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

<html>

<body>

<%

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

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

 %>

<table width="100%" border="0"cellpadding="0" cellspacing="0">

  <tr>

    <td width="17"valign="top" background="images/mail_leftbg.gif"><imgsrc="images/left-top-right.gif" width="17"height="29" /></td>

    <td valign="top"background="images/content-bg.gif"><tablewidth="100%" height="31" border="0"cellpadding="0" cellspacing="0"class="left_topbg" id="table2">

      <tr>

        <td height="31"><divclass="titlebt">员工相片上传</div></td>

      </tr>

    </table></td>

    <td width="16"valign="top" background="images/mail_rightbg.gif"><imgsrc="images/nav-right-bg.gif" width="16"height="29" /></td>

  </tr>

  <tr>

    <td valign="middle"background="images/mail_leftbg.gif">&nbsp;</td>

    <td valign="top"bgcolor="#eef2f6">

   

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

    <table width="100%"border="1" cellpadding="0" cellspacing="0"bordercolor="#a7c5ca">

  <tr bgcolor="#c0dde3">

    <th scope="col"width="25%">&nbsp;</th>

    <th scope="col"width="15%">&nbsp;</th>

    <th scope="col"width="35%">&nbsp;</th>

    <th scope="col"width="25%">&nbsp;</th>

    </tr>

  <tr>

    <td>&nbsp;</td>

    <td>员工ID&nbsp;</td>

    <td><label>

      <inputtype="text" name="id" value="<%=id %>">

    </label></td>

    <td>&nbsp;</td>

    </tr>

    <tr>

    <td>&nbsp;</td>

    <td>员工姓名:</td>

    <td><label>

      <inputtype="text" name="username" value="<%=username%>">

    </label></td>

    <td>&nbsp;</td>

    </tr>

    <tr>

    <td>&nbsp;</td>

    <td>员工相片:</td>

    <td><label>

      <inputtype="file" name="file1">

    </label></td>

    <td>&nbsp;</td>

    </tr>

    <tr>

    <td>&nbsp;</td>

    <td>&nbsp;</td>

    <td>

      <label>

        <inputtype="submit" name="Submit" value="提交">

        </label>

 

    </td>

    <td>&nbsp;</td>

    </tr>

</table>

    </form>

    </td>

    <tdbackground="images/mail_rightbg.gif">&nbsp;</td>

  </tr>

  <tr>

    <td valign="bottom"background="images/mail_leftbg.gif"><imgsrc="images/buttom_left2.gif" width="17"height="17" /></td>

    <tdbackground="images/buttom_bgs.gif"><imgsrc="images/buttom_bgs.gif" width="17"height="17"></td>

    <td valign="bottom"background="images/mail_rightbg.gif"><imgsrc="images/buttom_right2.gif" width="16"height="17" /></td>

  </tr>

</table>

</body>

</html>

 

 

 

 

 

可以看到,我们将数据提交到工程下的FileUpLoad这个Servlet。 之后,我们就来编写这个ServletFileUpLoad.java 

FileUpLoad.java代码如下:

package com.xtwy.hr.servlet;

import java.io.*;

import java.util.List;

import javax.servlet.ServletException;

import javax.servlet.http.HttpServlet;

import javax.servlet.http.HttpServletRequest;

importjavax.servlet.http.HttpServletResponse;

importorg.apache.commons.fileupload.FileItem;

importorg.apache.commons.fileupload.FileUploadException;

importorg.apache.commons.fileupload.disk.DiskFileItemFactory;

import org.apache.commons.fileupload.servlet.ServletFileUpload;

import com.xtwy.hr.dao.UsersDao;

 

public class FileUpLoad extendsHttpServlet {

       publicvoid doPost(HttpServletRequest request, HttpServletResponse response)

                     throwsServletException, IOException {

              request.setCharacterEncoding("utf-8");// 设置编码

              Stringphotoname = null;

              Stringid = null;

              //获得磁盘文件条目工厂

              DiskFileItemFactoryfactory = new DiskFileItemFactory();

              //获取文件需要上传到的路径

              Stringpath = request.getRealPath("/upload");

              //如果没以下两行设置的话,上传大的文件会占用很多内存,

              //设置暂时存放的存储室 , 这个存储室,可以和最终存储文件的目录不同

              factory.setRepository(newFile(path));

              //设置缓存的大小,当上传文件的容量超过该缓存时,直接放到暂时存储室

              factory.setSizeThreshold(1024* 1024);

              //高水平的API文件上传处理

              ServletFileUploadupload = new ServletFileUpload(factory);

              try{

                     //可以上传多个文件

                     List<FileItem>list = (List<FileItem>) upload.parseRequest(request);

                     for(FileItem item : list) {

                            Stringname = item.getFieldName(); // 获取表单的属性名字

                            if("id".equals(name)) {

                                   id= item.getString();

                            }

                            //如果获取的表单信息是普通的文本信息

                            if(item.isFormField()) {

                                   //获取用户具体输入的字符串,名字起得挺好,因为表单提交过来的是字符串类型的

                                   Stringvalue = item.getString();

                                   request.setAttribute(name,value);

                            }

                            //对传入的非简单的字符串进行处理,比如说二进制的图片,电影这些

                            else{

                                   /**

                                    * 以下三步,主要获取上传文件的名字

                                    */

                                   //获取路径名

                                   Stringvalue = item.getName();

                                   //索引到最后一个反斜杠

                                   intstart = value.lastIndexOf("\\");

                                   //截取上传文件的字符串名字,加1去掉反斜杠,

                                   Stringfilename = value.substring(start + 1);

                                   if("file1".equals(name)) {

                                          photoname= filename;

                                   }

                                   request.setAttribute(name,filename);

                                   OutputStreamout = new FileOutputStream(new File(path,

                                                 filename));

                                   InputStreamin = item.getInputStream();

                                   intlength = 0;

                                   byte[]buf = new byte[1024];

                                   System.out.println("获取上传文件的总共的容量:" + item.getSize());

                                   //in.read(buf) 每次读到的数据存放在 buf 数组中

                                   while((length = in.read(buf)) != -1) {

                                          // buf 数组中取出数据写到(输出流)磁盘上

                                          out.write(buf,0, length);

                                   }

                                   in.close();

                                   out.close();

                            }

                     }

              }catch (FileUploadException e) {

                     e.printStackTrace();

              }catch (Exception e) {

              }

              UsersDaouserdao = new UsersDao();

              userdao.updatePhotoById(Integer.parseInt(id),photoname);

              Listlist1 = null;

              list1= userdao.selectuserById(Integer.parseInt(id));

              request.setAttribute("userlist",list1);

              request.getRequestDispatcher("userview.jsp").forward(request,response);

       }

}

 

因为已对代码做了详细的注释,所以相信大家也能基本上传的这个过程。此外,也可以读取选择文件的后缀来筛选出可以上传的类型,需要更加复杂业务操作处理的,可以在Servlet进行修改和调用相关的JavaBean封装类。这些代码大家自己扩展,不再细谈。

上传结束之后,使页面转到上传成功页面userview.jsp进行查看。 当用户看到此页面时,说明你已实现文件的上传功能。

 


你可能感兴趣的:(文件上传,图片上传,JSP+Servlet图片上传,JSP图片上传)