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 ...
随机推荐
- WPF界面设计技巧(1)—不规则窗体图文指南
原文:WPF界面设计技巧(1)-不规则窗体图文指南 初到园子,奉上第一篇入门级教程,请勿见笑. 以往WinForm编程中,实现不规则窗体是有一定难度的,更难的是不规则窗体的边缘抗锯齿及局部透明处理.而 ...
- c++自带倒置数组函数
#include<stdio.h> #include <vector> #include <queue> #include<algorithm> usi ...
- sort 工具总结
sort的工作原理 sort将文件的每一行作为一个单位,相互比较,比较原则是从首字符向后,依次按ASCII码值进行比较,最后将他们按升序输出. -u 去除重复行 -r sort默认的排序方式是升序,如 ...
- 基于.net开发chrome核心浏览器【一】
原文:基于.net开发chrome核心浏览器[一] 说明: 这是本系列的第一篇文章,我会尽快发后续的文章. 源起 1.加快葬送IE6浏览器的进程 世界上使用IE6浏览器最多的地方在中国 中国使用IE6 ...
- js 自定义方法 实现停留几秒 sleep
function sleep(numberMillis) { var now = new Date(); var exitTime = now.getTime() + numberMillis; wh ...
- java 常用的包 默认导入的包
1.java.lang----包含一些Java语言的核心类,如String.Math.Integer.System和Thread,提供常用功能. 2.java.awt----包含了构成抽象窗口工具集( ...
- http://java.sun.com/jsp/jstl/core cannot be resolved in either web.xml or the jar files deployed wit
异常:The absolute uri: http://java.sun.com/jsp/jstl/core cannot be resolved in either web.xml or the j ...
- Naive Bayes Classification
Maching Learning QQ群:2 请说明来自csdn 微信:soledede
- Windows上的的神技
Windows上的的神技 不用借助任何第三方软件,其实Windows也大有可为——比你目前了解得至少要多得多,强大技能快来get起来! 1.文件隐藏谁的电脑里没点小秘密?东藏西藏到最后自己都找不到了有 ...
- cocos2d-x3.0数据结构
1.cocos2d::Vector 1.头报价"CCVector.h"头文件. 2.保存的数据类型必须是cocos2d::Ref的子类. 3.实现是动态加入数据集合即链表.主要的使 ...