Servlet上传文件
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上传文件的更多相关文章
- 使用Servlet上传文件
使用浏览器向服务器上传文件其本质是打开了一个长连接并通过TCP方式传输数据.而需要的动作是客户端在表单中使用file域,并指定该file域的name值,然后在form中设定enctype的值为mult ...
- 原生Servlet 上传文件
依赖jar <dependency> <groupId>commons-fileupload</groupId> <artifactId>commons ...
- java servlet上传文件并把文件内容显示在网页中
servlet3.0(JDK1.6)自带的API即可实现本地文件的上传,Servlet3.0新增了Part接口,HttpServletRequest的getPart()方法取得Part实现对象.下面我 ...
- servlet上传文件报错(三)
1.具体报错如下 null null Exception in thread "http-apr-8686-exec-5" java.lang.OutOfMemoryError: ...
- 5.servlet 上传文件
一.maven依赖 <dependency> <groupId>commons-fileupload</groupId> <artifactId>com ...
- JSP && Servlet | 上传文件
在WebContent下新建index.jsp 要点: 1. 表单 method 属性应该设置为 POST 方法,不能使用 GET 方法. 2. 表单 enctype 属性应该设置为 multip ...
- J2EE:Servlet上传文件到服务器,并相应显示
Servlet 可以与HTML一起使用来允许用户上传文件到服务器 编辑上传文件的页面upload.html 注意事项:上传方式使用POST不能使用GET(GET不能上传文件) 表单 enctype 属 ...
- servlet上传文件报错(二)
1.具体报错如下: java.io.FileNotFoundException: D:\MyEclipse\workspace\FileUpload\WebRoot\upload (拒绝访问.) at ...
- JAVA servlet 上传文件(commons-fileupload, commons-io)
<1>获取二进制文件流并输出 InputStream inputStream = request.getInputStream(); BufferedReader reader = new ...
随机推荐
- MySQL的一些基本操作
近期開始学习MySQL,主要是通过书籍,和看燕十八老师的视频,然后通过博客记录自己的学习过程. 登入数据库 zhiniaobu@telunsu-K55VD:~$ mysql -uroot -p Ent ...
- 使用Visual Studio 寻找App性能瓶颈
使用Visual Studio 寻找App性能瓶颈 最后更新日期:2014-05-05 阅读前提: 环境:Windows 8.1 64bit英文版,Visual Studio 2013 专业版Upda ...
- 经常使用vi编辑命令
进入 vi 该命令 vi filename :打开或新建文件.在第一行和第一光标 vi +n filename :打开文件,并将光标置于第 n 行首 vi + filename :打开文件,并将 ...
- 写代码质量改善java计划151建议——导航开始
2014-05-16 09:08 by Jeff Li 前言 系列文章:[传送门] 下个星期度过这几天的奋战,会抓紧java的进阶学习.听过一句话,大哥说过,你一个月前的代码去看下,慘不忍睹是吧.确实 ...
- 记得有一个奇怪的ORA-04028: cannot generate diana for object
开发商称新一package,目前已经在翻译过程中的一些错误.提示PL/SQL:ORA-00942: table or view does not exists.这是一个非常明显的错误,即要么是表不存在 ...
- Cordova CLI源码分析(二)——package.json
每个包需要在其顶层目录下包含一个package.json文件,该文件不仅是包的说明,也影响npm安装包时的配置选项 更多参数详见参考文档https://npmjs.org/doc/json.html ...
- 用数组array代替CActiveRecord构建CArrayDataProvider
当需要构建 GridView的时候: 常常用 CArrayDataProvider 或者 CActiveDataProvider 这是就需要一个CActiveRecord 比如: 857 ...
- oracle 转 mysql 最新有效法(转)
关键字:Oracle 转 MySQL . Oracle TO MySQL 没事试用了一下Navicat家族的新产品Navicat Premium,他集 Oracle.MySQL和PostgreSQL管 ...
- SQLSERVER图片查看工具SQL Image Viewer5.5.0.156
原文:SQLSERVER图片查看工具SQL Image Viewer5.5.0.156 SQLSERVER图片查看工具SQL Image Viewer5.5.0.156 在2013年某一次北京SQL ...
- Net 高效开发
Net 高效开发之不可错过的实用工具 工欲善其事,必先利其器,没有好的工具,怎么能高效的开发出高质量的代码呢?本文为各ASP.NET 开发者介绍一些高效实用的工具,涉及SQL 管理,VS插件,内存 ...