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 ...
随机推荐
- Mongodb数据备份恢复
Mongodb数据备份恢复 一.MongoDB数据库导入导出操作 1.导出数据库 twangback为备份的文件夹 命令: mongodump -h 127.0.0.1[服务器IP] -d advie ...
- Android画图监听接口OnPreDrawListener具体解释
public static interface ViewTreeObserver.OnPreDrawListener 我们先看下API中的定义: 类概述: 为即将绘制视图树时运行的回调函数定义的接口. ...
- poj3694(动态询问割桥的数目)
给我们一个图,然后有q次加边的操作,问每次加完边之后有多少个桥存在 首先用dfs求出所有的桥,然后dfs的过程中生成了一棵dfs树,该树有的边是桥,有的不是,用bridge[v] = true , 表 ...
- lambda left join .DefaultIfEmpty
我们知道lambda表达式在Linq to sql 和 Entity framework 中使用join函数可以实现inner join,那么怎么才能在lambda表达式中实现left join呢?秘 ...
- HDU4309-Seikimatsu Occult Tonneru(最大流)
Seikimatsu Occult Tonneru Time Limit: 12000/6000 MS (Java/Others) Memory Limit: 32768/32768 K (Ja ...
- vultr centos x64 6.5.x 升级php7.0
升级前,先卸载 php5.6.x 卸载php5.6.2 从cent 6.5.x 需要卸载: yum remove php56u-mysqlnd-5.6.20-1.ius.centos6.x86_64 ...
- 【leetcode】LRU
import java.util.HashMap; import java.util.Map; public class LRUCache { private int capacity; privat ...
- The app references non-public selectors in payload With Xcode6.1
猴子原创,欢迎转载.转载请注明: 转载自Cocos2D开发网–Cocos2Dev.com,谢谢! 原文地址: p=591" style="color: rgb(255, 97, 0 ...
- LNMP 免安装包
LNMP(Linux-Nginx-Mysql-PHP)可爱的黄金搭档,不过配置并不轻易,而我平常用于测试环境又经常用到,所以打包了这么一个免安装的LNMP包,内置常用库和模块,以及基本的优化设置,这样 ...
- iOS UIWebView 载入https 网站出现NSURLConnection/CFURLConnection HTTP load failed (kCFStreamErrorDomainSSL,
今天在载入https网站的时候遇到例如以下的错误问题.所以对自己之前写的iOS内嵌webview做了一些改动,能够让它载入http网站也能够让它载入https网站. 以下是我载入https网站的时候出 ...