JavaWeb -- 文件上传下载示例
1. 上传简单示例
Jsp
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>文件上传下载</title>
</head>
<body> <form action="${pageContext.request.contextPath}/UploadServlet" enctype="multipart/form-data" method="post">
上传用户:<input type="text" name="username" /> <br />
上传文件1:<input type="file" name="file1" /> <br />
上传文件2:<input type="file" name="file2" /> <br />
<input type="submit" value="上传 "/>
</form> <br />
${requestScope.message} </body>
</html>
Servlet
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException { try{ //1.得到解析器工厂
DiskFileItemFactory factory = new DiskFileItemFactory(); //2.得到解析器
ServletFileUpload upload = new ServletFileUpload(factory); //3.判断上传表单的类型
if(!upload.isMultipartContent(request)){
//上传表单为普通表单,则按照传统方式获取数据即可
return;
} //为上传表单,则调用解析器解析上传数据
List<FileItem> list = upload.parseRequest(request); //FileItem //遍历list,得到用于封装第一个上传输入项数据fileItem对象
for(FileItem item : list){ if(item.isFormField()){
//得到的是普通输入项
String name = item.getFieldName(); //得到输入项的名称
String value = item.getString();
System.out.println(name + "=" + value);
}else{
//得到上传输入项
String filename = item.getName(); //得到上传文件名 C:\Documents and Settings\ThinkPad\桌面\1.txt
filename = filename.substring(filename.lastIndexOf("\\")+1);
InputStream in = item.getInputStream(); //得到上传数据
int len = 0;
byte buffer[]= new byte[1024]; //用于保存上传文件的目录应该禁止外界直接访问
String savepath = this.getServletContext().getRealPath("/WEB-INF/upload");
System.out.println(savepath); FileOutputStream out = new FileOutputStream(savepath + "/" + filename); //向upload目录中写入文件
while((len=in.read(buffer))>0){
out.write(buffer, 0, len);
} in.close();
out.close();
request.setAttribute("message", "上传成功");
}
} }catch (Exception e) {
request.setAttribute("message", "上传失败");
e.printStackTrace();
} }
2. 修改后的上传功能:
注意事项:
1、上传文件名的中文乱码和上传数据的中文乱码
upload.setHeaderEncoding("UTF-8"); //解决上传文件名的中文乱码
//表单为文件上传,设置request编码无效,只能手工转换
1.1 value = new String(value.getBytes("iso8859-1"),"UTF-8");
1.2 String value = item.getString("UTF-8"); 2.为保证服务器安全,上传文件应该放在外界无法直接访问的目录 3、为防止文件覆盖的现象发生,要为上传文件产生一个唯一的文件名 4、为防止一个目录下面出现太多文件,要使用hash算法打散存储 5.要限制上传文件的最大值,可以通过:
ServletFileUpload.setFileSizeMax(1024)
方法实现,并通过捕获:
FileUploadBase.FileSizeLimitExceededException异常以给用户友好提示 6.想确保临时文件被删除,一定要在处理完上传文件后,调用item.delete方法 7.要限止上传文件的类型:在收到上传文件名时,判断后缀名是否合法 8、监听文件上传进度:
ServletFileUpload upload = new ServletFileUpload(factory);
upload.setProgressListener(new ProgressListener(){
public void update(long pBytesRead, long pContentLength, int arg2) {
System.out.println("文件大小为:" + pContentLength + ",当前已处理:" + pBytesRead);
}
}); 9. 在web页面中动态添加文件上传输入项
function addinput(){
var div = document.getElementById("file"); var input = document.createElement("input");
input.type="file";
input.name="filename"; var del = document.createElement("input");
del.type="button";
del.value="删除";
del.onclick = function d(){
this.parentNode.parentNode.removeChild(this.parentNode);
} var innerdiv = document.createElement("div"); innerdiv.appendChild(input);
innerdiv.appendChild(del); div.appendChild(innerdiv);
}
上传jsp:
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>My JSP 'upload2.jsp' starting page</title> <script type="text/javascript">
function addinput(){
var div = document.getElementById("file"); var input = document.createElement("input");
input.type="file";
input.name="filename"; var del = document.createElement("input");
del.type="button";
del.value="删除";
del.onclick = function d(){
this.parentNode.parentNode.removeChild(this.parentNode);
} var innerdiv = document.createElement("div"); innerdiv.appendChild(input);
innerdiv.appendChild(del); div.appendChild(innerdiv);
}
</script> </head> <body> <form action="" enctype="mutlipart/form-data"></form>
<table>
<tr>
<td>上传用户:</td>
<td><input type="text" name="username"></td>
</tr>
<tr>
<td>上传文件:</td>
<td>
<input type="button" value="添加上传文件" onclick="addinput()">
</td>
</tr>
<tr>
<td></td>
<td>
<div id="file"> </div>
</td>
</tr> </table> </body>
</html>
上传servlet
public class UploadServlet1 extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
//request.getParameter("username"); //****错误
request.setCharacterEncoding("UTF-8"); //表单为文件上传,设置request编码无效
//得到上传文件的保存目录
String savePath = this.getServletContext().getRealPath("/WEB-INF/upload");
try{
DiskFileItemFactory factory = new DiskFileItemFactory();
factory.setRepository(new File(this.getServletContext().getRealPath("/WEB-INF/temp")));
ServletFileUpload upload = new ServletFileUpload(factory);
/*upload.setProgressListener(new ProgressListener(){
public void update(long pBytesRead, long pContentLength, int arg2) {
System.out.println("文件大小为:" + pContentLength + ",当前已处理:" + pBytesRead);
}
});*/
upload.setHeaderEncoding("UTF-8"); //解决上传文件名的中文乱码
if(!upload.isMultipartContent(request)){
//按照传统方式获取数据
return;
}
/*upload.setFileSizeMax(1024);
upload.setSizeMax(1024*10);*/
List<FileItem> list = upload.parseRequest(request);
for(FileItem item : list){
if(item.isFormField()){
//fileitem中封装的是普通输入项的数据
String name = item.getFieldName();
String value = item.getString("UTF-8");
//value = new String(value.getBytes("iso8859-1"),"UTF-8");
System.out.println(name + "=" + value);
}else{
//fileitem中封装的是上传文件
String filename = item.getName(); //不同的浏览器提交的文件是不一样 c:\a\b\1.txt 1.txt
System.out.println(filename);
if(filename==null || filename.trim().equals("")){
continue;
}
filename = filename.substring(filename.lastIndexOf("\\")+1);
InputStream in = item.getInputStream();
String saveFilename = makeFileName(filename); //得到文件保存的名称
String realSavePath = makePath(saveFilename, savePath); //得到文件的保存目录
FileOutputStream out = new FileOutputStream(realSavePath + "\\" + saveFilename);
byte buffer[] = new byte[1024];
int len = 0;
while((len=in.read(buffer))>0){
out.write(buffer, 0, len);
}
in.close();
out.close();
item.delete(); //删除临时文件
}
}
}catch (FileUploadBase.FileSizeLimitExceededException e) {
e.printStackTrace();
request.setAttribute("message", "文件超出最大值!!!");
request.getRequestDispatcher("/message.jsp").forward(request, response);
return;
}
catch (Exception e) {
e.printStackTrace();
}
}
public String makeFileName(String filename){ //2.jpg
return UUID.randomUUID().toString() + "_" + filename;
}
public String makePath(String filename,String savePath){
int hashcode = filename.hashCode();
int dir1 = hashcode&0xf; //0--15
int dir2 = (hashcode&0xf0)>>4; //0-15
String dir = savePath + "\\" + dir1 + "\\" + dir2; //upload\2\3 upload\3\5
File file = new File(dir);
if(!file.exists()){
file.mkdirs();
}
return dir;
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
}
}
3. 下载功能
//列出网站所有下载文件
public class ListFileServlet extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException { String filepath = this.getServletContext().getRealPath("/WEB-INF/upload");
Map map = new HashMap();
listfile(new File(filepath),map); request.setAttribute("map", map);
request.getRequestDispatcher("/listfile.jsp").forward(request, response);
} public void listfile(File file,Map map){ if(!file.isFile()){
File files[] = file.listFiles();
for(File f : files){
listfile(f,map);
}
}else{
String realname = file.getName().substring(file.getName().indexOf("_")+1); //9349249849-88343-8344_阿_凡_达.avi
map.put(file.getName(), realname);
} } public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException { doGet(request, response);
} }
jsp显示
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>My JSP 'listfile.jsp' starting page</title>
</head> <body> <c:forEach var="me" items="${map}">
<c:url value="/servlet/DownLoadServlet" var="downurl">
<c:param name="filename" value="${me.key}"></c:param>
</c:url>
${me.value } <a href="${downurl}">下载</a> <br/>
</c:forEach> </body>
</html>
下载处理servlet
public class DownLoadServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String filename = request.getParameter("filename"); //23239283-92489-阿凡达.avi
filename = new String(filename.getBytes("iso8859-1"),"UTF-8");
String path = makePath(filename,this.getServletContext().getRealPath("/WEB-INF/upload"));
File file = new File(path + "\\" + filename);
if(!file.exists()){
request.setAttribute("message", "您要下载的资源已被删除!!");
request.getRequestDispatcher("/message.jsp").forward(request, response);
return;
}
String realname = filename.substring(filename.indexOf("_")+1);
response.setHeader("content-disposition", "attachment;filename=" + URLEncoder.encode(realname, "UTF-8"));
FileInputStream in = new FileInputStream(path + "\\" + filename);
OutputStream out = response.getOutputStream();
byte buffer[] = new byte[1024];
int len = 0;
while((len=in.read(buffer))>0){
out.write(buffer, 0, len);
}
in.close();
out.close();
}
public String makePath(String filename,String savePath){
int hashcode = filename.hashCode();
int dir1 = hashcode&0xf; //0--15
int dir2 = (hashcode&0xf0)>>4; //0-15
String dir = savePath + "\\" + dir1 + "\\" + dir2; //upload\2\3 upload\3\5
File file = new File(dir);
if(!file.exists()){
file.mkdirs();
}
return dir;
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
}
}
JavaWeb -- 文件上传下载示例的更多相关文章
- JavaWeb 文件 上传 下载
文件上传下载对于一个网站来说,重要性不言而喻.今天来分享一个JavaWeb方式实现的文件上传下载的小例子. 项目依赖 项目目录 工作流程 文件上传 表单处的设置 服务器端 上传功能的实现 upload ...
- JavaWeb 文件上传下载
1. 文件上传下载概述 1.1. 什么是文件上传下载 所谓文件上传下载就是将本地文件上传到服务器端,从服务器端下载文件到本地的过程.例如目前网站需要上传头像.上传下载图片或网盘等功能都是利用文件上传下 ...
- 转载:JavaWeb 文件上传下载
转自:https://www.cnblogs.com/aaron911/p/7797877.html 1. 文件上传下载概述 1.1. 什么是文件上传下载 所谓文件上传下载就是将本地文件上传到服务器端 ...
- JavaWeb实现文件上传下载功能实例解析
转:http://www.cnblogs.com/xdp-gacl/p/4200090.html JavaWeb实现文件上传下载功能实例解析 在Web应用系统开发中,文件上传和下载功能是非常常用的功能 ...
- JavaWeb实现文件上传下载功能实例解析 (好用)
转: JavaWeb实现文件上传下载功能实例解析 转:http://www.cnblogs.com/xdp-gacl/p/4200090.html JavaWeb实现文件上传下载功能实例解析 在Web ...
- SpringMVC ajax技术无刷新文件上传下载删除示例
参考 Spring MVC中上传文件实例 SpringMVC结合ajaxfileupload.js实现ajax无刷新文件上传 Spring MVC 文件上传下载 (FileOperateUtil.ja ...
- .JavaWeb文件上传和FileUpload组件使用
.JavaWeb文件上传 1.自定义上传 文件上传时的表单设计要符合文件提交的方式: 1.提交方式:post 2.表单中有文件上传的表单项:<input type="file" ...
- commons-fileupload实现文件上传下载
commons-fileupload是Apache提供的一个实现文件上传下载的简单,有效途径,需要commons-io包的支持,本文是一个简单的示例 上传页面,注意设置响应头 <body> ...
- JAVA Web 之 struts2文件上传下载演示(一)(转)
JAVA Web 之 struts2文件上传下载演示(一) 一.文件上传演示 1.需要的jar包 大多数的jar包都是struts里面的,大家把jar包直接复制到WebContent/WEB-INF/ ...
随机推荐
- Coursera课程《Machine Learning》学习笔记(week2)
1 特征 1-1 什么是特征? 我的理解就是,用于描述某个样本点,以哪几个指标来评定,这些个指标就是特征.比方说对于一只鸟,我们评定的指标就可以是:(a)鸟的翅膀大还是小?(b)鸟喙长还是短?(c)鸟 ...
- grafana-----Annotation
注释提供了一个方法,在丰富的活动中做个标志点.当你鼠标移到这个注释上,你可以得到title,tags,和text information的事件. Queries 注释事件获得是通过一个注释查询.打开d ...
- 烂代码 git blame
关于烂代码的那些事(上) - Axb的自我修养 http://blog.2baxb.me/archives/1343 关于烂代码的那些事(上) 六月 21, 2015 57 条评论 目录 [显示] 1 ...
- iOS 多线程之 NSOperation 的基本使用
1.NSOperation,NSOperationQueue 简介 NSOperation,NSOperationQueue是苹果提供给我们的一套多线程解决方案.实际上 NSOperation.NSO ...
- Python菜鸟之路:Django CSRF跨站请求伪造
前言 CSRF,Cross-site request forgery跨站请求伪造,也被称为“One Click Attack”或者Session Riding,通常缩写为CSRF或者XSRF,是一种对 ...
- 处理 Java 的“Cannot allocate memory”错误
今天在配置 DCA 服务器的时候,检验 java 版本的时候忽然遇到了一个 Cannot allocate memory 错误 [root@elcid-prod1 ~]# java -version ...
- MySQL中锁的类型
InnoDB存储引擎实现了一下两种标准的行级锁: 共享锁S LOCK 允许事务读一行数据 排他锁 X LOCK 允许事务删除或更新一行数据 如果是一个事务T1斤获得了行r的共享锁,那么另外一个事务T2 ...
- 0x04 MySQl 表操作
0x01 存储引擎介绍 存储引擎即表类型,mysql根据不同的表类型会有不同的处理机制 详见:http://www.cnblogs.com/linhaifeng/articles/7213670.ht ...
- MDF损坏或LDF文件损坏
MDF损坏或LDF损坏 MDF丢失或LDF丢失 注意,这些情况必须要相同版本的sql server才能操作成功 当MDF损坏时 1.备份结尾日志 http://www.cnblogs.com/gere ...
- vue-cli 搭建项目
1.cnpm install -g vue-cli 2.vue -V(注意大写,查vue版本) 3.vue init webpack vue1(创建vue1目录) 4.cd vue1(定位到目录中) ...