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 ...
随机推荐
- 使用GraceNote Web API发展Mac发现音乐信息的应用
好久没有写博客,最近各种忙,特别忙里忙,今晚难得清闲.写最近完成下一个博客任务的摘要:使用GraceNote的Web API开发一个查询的音乐信息的应用,事实上,并在这些功能的前GraceNote S ...
- VMware vSphere 服务器虚拟化之二十七桌面虚拟化之View中使用Thinapp软件虚拟化
VMware vSphere 服务器虚拟化之二十七桌面虚拟化之View中使用Thinapp软件虚拟化 VMware ThinApp 应用程序虚拟化软件是无代理解决方案,通过将应用程序隔离并封装为EXE ...
- net平台下连接池
http://www.cnblogs.com/visionwang/archive/2012/11/16/2774203.html net平台下连接池概述 ADO.NET已经为我们提供这样的连接池管理 ...
- win7下硬盘安装win7+linuxUbuntu双系统方法
Linux安装大致介绍: win7下硬盘安装win7+linuxUbuntu双系统方法 原则: 所有的看完在装,请仔细看 一 条件: 1. 系统选择 linux unbuntu12.04.2-desk ...
- Html A标签中 href 和 onclick用法、区别、优先级别
原文:Html A标签中 href 和 onclick用法.区别.优先级别 如果不设置 href属性在IE6下面会不响应hover.双击后会选中标签的父容器而非这个一a标签(IE下都存在这一问题). ...
- 搜索树SVN的树的时候遇到的乱码问题
public void listDirectoryNode(SVNRepository repository, String dirUrl, FileNode node) { String curre ...
- java实现简单web服务器(分析+源代码)
在日常的开发中,我们用过很多开源的web服务器,例如tomcat.apache等等.现在我们自己实现一个简单的web服务器,基本的功能就是用户点击要访问的资源,服务器将资源发送到客户端的浏览器.为了简 ...
- 超炫HTML5 SVG聊天框拖拽弹性摇摆动画特效
这是一款很有创意的HTML5 SVG聊天框拖拽弹性摇摆动画特效. 用户能够用鼠标点击或用手滑动聊天框上的指定区域,该区域会以很有弹性的弹簧效果拉开聊天用户列表.点击一个用户头像后.又以同样的弹性特效切 ...
- [WPF]不规则窗体的实现
Microsoft Expression Design 4 导入做好的login.Png图片 调整美工板大小 导出,右边格式为XAML WPF 资源字典,实时效果为XAML效果 文件名login.xa ...
- quick-cocos2d-x游戏开发【7】——scheduler 定时器
定时器用的地方还是比較多的,游戏中的逻辑推断非常多都是採用每帧运行.quick对于schedule的封装在scheduler这个lua文件里.假设是第一次接触quick的话,可能依照官方的api来写一 ...