JSP && Servlet | 上传文件
在WebContent下新建index.jsp
要点:
1. 表单 method 属性应该设置为 POST 方法,不能使用 GET 方法。
2. 表单 enctype 属性应该设置为 multipart/form-data,只有使用enctype="multipart/form-data",表单才会把文件的内容编码到HTML请求中。
3. 上传单个文件,应该使用单个带有属性 type="file" 的 <input .../> 标签。为了允许多个文件上传,请包含多个 name 属性值不同的 input 标签。输入标签具有不同的名称属性的值。浏览器会为每个 input 标签关联一个浏览按钮。
<%@ page language="java" contentType="text/html; charset=utf-8"
pageEncoding="utf-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Insert title here</title>
</head>
<body>
<form action="upload" method="post" enctype="multipart/form-data"> 请选择上传的图片或文件:
<input type="file" name="fileName"/> <input type="submit" value="上传"/>
</form>
</body>
</html>
编写Servlet 处理表单请求:
需要两个jar包,
manven引入:
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.3.2</version>
</dependency>
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.5</version>
</dependency>
package servlet; import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.List; import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
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; @WebServlet(value="/upload")
public class Upload extends HttpServlet{ @Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { porcess(req, resp);
} @Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { porcess(req, resp);
} public void porcess(HttpServletRequest req,HttpServletResponse resp) throws ServletException, IOException {
req.setCharacterEncoding("utf-8");
resp.setContentType("text/html;charset=utf-8");
//创建一个解析器工厂
DiskFileItemFactory factory = new DiskFileItemFactory();
// 设置内存临界值 - 超过后将产生临时文件并存储于临时目录中 4M
factory.setSizeThreshold(1024*1024*4);
//创建解析类的实例,文件上传解析器
ServletFileUpload sfu = new ServletFileUpload(factory);
//开始解析
//设置上传文件的最大值(单个文件) 60M
sfu.setFileSizeMax(1024*1024*60);
// 设置最大请求值 (包含文件和表单数据)
sfu.setSizeMax(1024*1024*70);
//每个表单域中数据会封装到一个对应的FileItem对象上
try { // sfu.parseRequest(req): 解析request对象,并把表单中的每一个输入项包装成一个fileItem 对象,并返回一个保存了所有FileItem的list集合。
List<FileItem> items = sfu.parseRequest(req); //区分表单域
for (FileItem item:items) {
//判断输入的类型是 普通输入项 还是文件,isFormField为true,表示这不是文件上传表单域
if(!item.isFormField()){
ServletContext sctx = getServletContext();
//获得存放文件的物理路径
//upload下的某个文件夹 得到当前在线的用户 找到对应的文件夹 String path = sctx.getRealPath("/upload");
System.out.println(path);
//获得文件名
String fileName = item.getName();
System.out.println(fileName); //该方法在某些平台(操作系统),会返回路径+文件名
fileName = fileName.substring(fileName.lastIndexOf("\\")+1);
File file = new File(path+"\\"+fileName); if(!file.exists()){
item.write(file);
req.setAttribute("message","文件上传成功!"); }
} else {
//普通输入项 ,得到input中的name属性的值
String name=item.getFieldName();
//得到输入项中的值
String value=item.getString("UTF-8");
System.out.println("name="+name+" value="+value);
}
}
} catch (Exception e) {
req.setAttribute("message","错误信息: " + e.getMessage());
} req.getRequestDispatcher("/WEB-INF/status.jsp").forward(req, resp); }
}
最新版本的 commons-fileupload.x.x.jar 文件。可以从 http://commons.apache.org/proper/commons-fileupload/ 下载。
最新版本的 commons-io-x.x.jar 文件。可以从 http://commons.apache.org/proper/commons-io/ 下载。
来源:
http://www.runoob.com/jsp/jsp-file-uploading.html JSP 文件上传
https://blog.csdn.net/qiyuexuelang/article/details/8861300 Servlet+Jsp实现图片或文件的上传功能
JSP && Servlet | 上传文件的更多相关文章
- Servlet上传文件
Servlet上传文件 1.准备工作 (1)利用FileUpload组件上传文件,须要到apache上下载commons-fileupload-1.3.1.jar 下载地址:http://common ...
- 原生Servlet 上传文件
依赖jar <dependency> <groupId>commons-fileupload</groupId> <artifactId>commons ...
- jsp+servlet上传excel并将数据导入到数据库表的实现方法
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding= ...
- 使用Servlet上传文件
使用浏览器向服务器上传文件其本质是打开了一个长连接并通过TCP方式传输数据.而需要的动作是客户端在表单中使用file域,并指定该file域的name值,然后在form中设定enctype的值为mult ...
- springMVC+jsp+ajax上传文件
工作中遇到的小问题,做个笔记 实现springMVC + jsp + ajax 上传文件 HTML <body> <form id="myform" method ...
- 【转】JSP使用上传文件,并生产高清缩略图示例
原文地址:http://blog.csdn.net/yakson/article/details/9875731 前言 刚开始本来只想来测试一下Thumbnails生成缩略图的效果的,顺便来学一下js ...
- java servlet上传文件并把文件内容显示在网页中
servlet3.0(JDK1.6)自带的API即可实现本地文件的上传,Servlet3.0新增了Part接口,HttpServletRequest的getPart()方法取得Part实现对象.下面我 ...
- 5.servlet 上传文件
一.maven依赖 <dependency> <groupId>commons-fileupload</groupId> <artifactId>com ...
- servlet上传文件报错(三)
1.具体报错如下 null null Exception in thread "http-apr-8686-exec-5" java.lang.OutOfMemoryError: ...
随机推荐
- git (转载)
文章转载 一:Git是什么? Git是目前世界上最先进的分布式版本控制系统. 二:SVN与Git的最主要的区别? SVN是集中式版本控制系统,版本库是集中放在中央服务器的,而干活的时候,用的都是自己的 ...
- Struts action
<action name="KnowledgeBankManageAction_*" class="knowledgeBankManageAction" ...
- 数据结构之 图论---连通分量的个数(dfs搜索)
数据结构实验:连通分量个数 Time Limit: 1000MS Memory limit: 65536K 题目描述 在无向图中,如果从顶点vi到顶点vj有路径,则称vi和vj连通.如果图中任意两个 ...
- Ubuntu安装基础教程
作者:TeliuTe 来源:基础教程网 二十三.安装Ubuntu14.04 返回目录 下一课 14.04 版安装与前面版本类似,学习中遇到不清楚的地方,可以参考一下前面的内容,操作中注意细心,下面来看 ...
- BZOJ 2023 [Usaco2005 Nov]Ant Counting 数蚂蚁:dp【前缀和优化】
题目链接:http://www.lydsy.com/JudgeOnline/problem.php?id=2023 题意: 有n个家族,共m只蚂蚁(n <= 1000, m <= 1000 ...
- codeforces C. Inna and Huge Candy Matrix 解题报告
题目链接:http://codeforces.com/problemset/problem/400/C 题目意思:给出一个n行m列的矩阵,问经过 x 次clockwise,y 次 horizontal ...
- Linux:普通用户不能执行ifconfig命令问题
有客户现场服务器禁用了root帐号,在普通帐号下,执行ifconfig,提示bash:ifconfig command not found: 导致业务系统无法用普通帐号获取ifcnofig的MAC地址 ...
- 通过 :hover 伪元素控制其他元素
---代码 <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <tit ...
- RTMP协议的理解
RTMP协议:real time message protocol 工作原理: 先采集摄像头视频和麦克风音频信息,再进行音视频的编码(mpeg),通过FMLE(Flash Media Live Enc ...
- poj1151 Atlantis——扫描线+线段树
题目:http://poj.org/problem?id=1151 经典的扫描线问题: 可以用线段树的每个点代表横向被矩形上下边分割开的每一格,这样将一个矩形的出现或消失化为线段树上的单点修改: 每个 ...