Servlet上传文件

1、准备工作

(1)利用FileUpload组件上传文件,须要到apache上下载commons-fileupload-1.3.1.jar

下载地址:http://commons.apache.org/fileupload/

(2)因为文件上传还得有IO流传输,须要到apache上下载commons-io-2.4.jar

下载地址:http://commons.apache.org/io/

2、正式开发

(1)新建文件上传界面

file.jsp:

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>"> <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"> </head> <body>
<form action="FileUploadServlet" method="post" enctype="multipart/form-data">
<table>
<tr>
<td>
<label for="username">用户名:</label>
<input type="text" name="username"/>
</td>
</tr>
<tr>
<td>
<label for="password">密  码:</label>
<input type="password" name="password"/>
</td>
</tr>
<tr>
<td>
        
<input type="file" name="fileOne" id="fileOne"/>
</td>
</tr>
<tr>
<td>
        
<input type="file" name="fileTwo" id="fileTwo"/>
</td>
</tr>
<tr>
<td>
        
<input type="submit" name="submit" id="submit" value="提交"/>
     
<input type="reset" name="reset" id="reset" value="重置"/>
</td>
</tr>
</table>
</form>
</body>
</html>

(2)新建文件上传成功界面

result.jsp:

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>">
<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"> </head> <body>
用户名:<%= request.getAttribute("username") %><br/>
密  码:<%= request.getAttribute("password") %><br/>
文件一:<%= request.getAttribute("fileOne") %><br/>
文件二:<%= request.getAttribute("fileTwo") %><br/>
</body>
</html>

(3)新建servlet进行文件上传处理

FileUploadServlet.java:

package com.you.file.servlet;

import java.io.File;
import java.io.IOException;
import java.util.List; import javax.servlet.ServletContext;
import javax.servlet.ServletException;
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.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload; public class FileUploadServlet extends HttpServlet
{
/**
* @Fields serialVersionUID:
*/
private static final long serialVersionUID = -3788743064732005240L; /**
* The doPost method of the servlet. <br>
*
* This method is called when a form has its tag value method equals to post.
*
* @param request the request send by the client to the server
* @param response the response send by the server to the client
* @throws ServletException if an error occurred
* @throws IOException if an error occurred
*/
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
/**
* 设置编码格式
*/
request.setCharacterEncoding("UTF-8");
/**
* 创建一个工厂类
*/
DiskFileItemFactory factory = new DiskFileItemFactory();
ServletContext context = getServletContext();
String path = context.getRealPath("/file");
/**
* 设置上传文件放在磁盘上的暂时文件夹
*/
factory.setRepository(new File(path));
/**
* 设置上传文件大小
*/
factory.setSizeThreshold(1024*1024); //上传对象
ServletFileUpload fileuplod = new ServletFileUpload(factory);
try
{
/**
* 解析各个表单域
*/
List<FileItem> list = fileuplod.parseRequest(request); for(FileItem item : list)
{
/**
* 推断是简单域 (item.isFormField()==true)
*/
if(item.isFormField())
{
//获得简单域的名字
String fieldName = item.getFieldName();
//获得简单域的值
String fieldValue = item.getString("UTF-8");
request.setAttribute(fieldName, fieldValue);
}
else//推断是文件域 (item.isFormField()==false)
{
//获得文件域的名字
String fieldName = item.getFieldName();
//获得文件域的值,带路径,即是路径+文件名称
String value = item.getName();
//取的文件域的值的名字,不带路径
int temp = value.lastIndexOf("\\");
String fieldValue = value.substring(temp+1);
//获得是file文件的内容
request.setAttribute(fieldName, fieldValue); //写入
item.write(new File(path,fieldValue));
}
}
}
catch (Exception e)
{
//e.printStackTrace();
}
/**
* 跳转到上传成功界面
*/
request.getRequestDispatcher("result.jsp").forward(request, response);
} /**
* Initialization of the servlet. <br>
* init方法
* @throws ServletException if an error occurs
*/
public void init() throws ServletException
{ } /**
* destroy方法
* Destruction of the servlet. <br>
*/
public void destroy()
{
super.destroy();
} /**
* The doGet method of the servlet. <br>
*
* This method is called when a form has its tag value method equals to get.
* doGet方法
* @param request the request send by the client to the server
* @param response the response send by the server to the client
* @throws ServletException if an error occurred
* @throws IOException if an error occurred
*/
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
this.doPost(request, response);
}
}

(3)配置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>
<servlet>
<description>This is the description of my J2EE component</description>
<display-name>This is the display name of my J2EE component</display-name>
<servlet-name>FileUploadServlet</servlet-name>
<servlet-class>com.you.file.servlet.FileUploadServlet</servlet-class> </servlet> <servlet-mapping>
<servlet-name>FileUploadServlet</servlet-name>
<url-pattern>/FileUploadServlet</url-pattern>
</servlet-mapping> <welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
</web-app>

3、过程演示

(1)初始化时

(2)输入username、password,上传文件

watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQveW91MjNoYWk0NQ==/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/gravity/Center" width="710" height="482" border="1" alt="">

(3)还未上传。项目中的file目录

(4)上传成功后,页面显示

watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQveW91MjNoYWk0NQ==/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/gravity/Center" width="176" height="99" border="1" alt="">

(5)上传成功后,file目录

版权声明:本文博主原创文章。博客,未经同意不得转载。

Servlet上传文件的更多相关文章

  1. 使用Servlet上传文件

    使用浏览器向服务器上传文件其本质是打开了一个长连接并通过TCP方式传输数据.而需要的动作是客户端在表单中使用file域,并指定该file域的name值,然后在form中设定enctype的值为mult ...

  2. 原生Servlet 上传文件

    依赖jar <dependency> <groupId>commons-fileupload</groupId> <artifactId>commons ...

  3. java servlet上传文件并把文件内容显示在网页中

    servlet3.0(JDK1.6)自带的API即可实现本地文件的上传,Servlet3.0新增了Part接口,HttpServletRequest的getPart()方法取得Part实现对象.下面我 ...

  4. servlet上传文件报错(三)

    1.具体报错如下 null null Exception in thread "http-apr-8686-exec-5" java.lang.OutOfMemoryError: ...

  5. 5.servlet 上传文件

    一.maven依赖 <dependency> <groupId>commons-fileupload</groupId> <artifactId>com ...

  6. JSP && Servlet | 上传文件

    在WebContent下新建index.jsp 要点: 1.  表单 method 属性应该设置为 POST 方法,不能使用 GET 方法. 2.  表单 enctype 属性应该设置为 multip ...

  7. J2EE:Servlet上传文件到服务器,并相应显示

    Servlet 可以与HTML一起使用来允许用户上传文件到服务器 编辑上传文件的页面upload.html 注意事项:上传方式使用POST不能使用GET(GET不能上传文件) 表单 enctype 属 ...

  8. servlet上传文件报错(二)

    1.具体报错如下: java.io.FileNotFoundException: D:\MyEclipse\workspace\FileUpload\WebRoot\upload (拒绝访问.) at ...

  9. JAVA servlet 上传文件(commons-fileupload, commons-io)

    <1>获取二进制文件流并输出 InputStream inputStream = request.getInputStream(); BufferedReader reader = new ...

随机推荐

  1. css3进行截取

    在css3出现之前,一般采用substring来进行截取,现在 不用js,纯css3也能进行截取了: text-overflow:clip | ellipsis 1.clip: 要在一定的高度内,配合 ...

  2. Libgdx: 将Texturepacker打包的PNG图片还原成一张一张的单个的

    你是否发现用Texturepacker在打包压缩资源文件之后. 把原稿文件弄丢了,可是又要添加新的小png的时候,却无从下手了,本文就是博主在遇到这个问题后百度了非常多方法,可惜仅仅有plist格式的 ...

  3. My Solution: Word Ladder

    public class Solution { public int ladderLength(String start, String end, Set<String> dict) { ...

  4. windows phone 7,sliverlight 下载网页的解析,关于wp7 gb2312编码

    原文:windows phone 7,sliverlight 下载网页的解析,关于wp7 gb2312编码 关于silverlight和wp7(windows phone 7)是默认不支持gb2312 ...

  5. java.lang.NullPointerException错误分析

    java.lang.NullPointerException是什么错误 你使用了空的指针.在java中虽然号称抛弃了C++中不安全的指针,但其实他所有的东西你都可以理解为指针.这种情况一般发生在你使用 ...

  6. hibernate之关于使用连接表实现多对一关联映射

    [Hibernate]之关于使用连接表实现多对一关联映射 在我们项目使用中採用中间表最多的一般就是多对一,或者是多对多,当然一对一使用中间表也是能够的,可是这样的几率通常少之又少!所以这里重点介绍多对 ...

  7. 参数化测试--sheet表的应用

    自动化测试对录制和编辑好的测试步骤进行回放,这种是线性的自动化测试方式,其缺点是明显的,就是其测试覆盖面比较低.测试回放的只是录制时做出的界面操作,以及输入的测试数据,或者是脚本编辑时指定的界面操作和 ...

  8. 样品GA的良好理解

    遗传算法演示样本手册模拟 为了更好地理解遗传算法的计算过程,法的各    个主要运行步骤.       例:求下述二元函数的最大值: (1) 个体编码           遗传算法的运算对象是表示个体 ...

  9. swift 学习资源 大集合

    今天看到一个swift学习网站,其中我们收集了大量的学习资源 Swift 介绍 Swift 介绍 来自 Apple 官方 Swift 简单介绍 (@peng_gong) 一篇不错的中文简单介绍 [译] ...

  10. 鸟书shell 学习笔记(一) shell专注于概念和命令

    变量   variableName=value 等号左右不能有空格 变量内容有空格须要用"或者'括起来,可是 v="hello $name" $保持原有功能,单引號则不行 ...