完成文件上传下载功能案例
来源:互联网 发布:不用网络的音乐播放器 编辑:程序博客网 时间:2024/06/05 01:05
上传的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 addfile(){
var files=document.getElementById("files");
var input=document.createElement("input");
input.type="file";
input.name="file";
var deletebutton=document.createElement("input");
deletebutton.type="button";
deletebutton.value="删除";
deletebutton.onclick= function del(){
this.parentNode.parentNode.removeChild(this.parentNode);
}
var div=document.createElement("div");
div.appendChild(input);
div.appendChild(deletebutton);
files.appendChild(div);
}
</script>
</head>
<body>
<form action="UploadServlet" method="post"
enctype="multipart/form-data">
<table>
<tr>
<td>
上传用户:
</td>
<td>
<input type="text" name="username" />
</td>
</tr>
<tr>
<td></td>
<td>
<input type="button" value="添加文件" onclick="addfile()"/>
</td>
</tr>
<tr>
<td></td>
<td id="files"></td>
</tr>
<tr>
<td colspan="2">
<input type="submit" value="上传" />
</td>
</tr>
</table>
</form>
</body>
</html>
处理上传请求的servlet----------------------
package com.hbsi.servlet;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.UUID;
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.FileUploadBase;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.ProgressListener;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import com.sun.security.sasl.ServerFactoryImpl;
public class UploadServlet extends HttpServlet {
private List fileType=Arrays.asList("txt","jpg","bmp");
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
try {
//创建一个解析工厂
DiskFileItemFactory factory = new DiskFileItemFactory();
String tempPath=this.getServletContext().getRealPath("temp");
factory.setRepository(new File(tempPath));
//得到一个解析器
ServletFileUpload upload = new ServletFileUpload(factory);
upload.setHeaderEncoding("UTF-8");
//upload.setFileSizeMax(1024*1024);//限制大小
upload.setProgressListener(new ProgressListener() {
@Override
public void update(long pBytesRend, long pContentLength, int pItems) {
System.out.println("上传文件的大小为:"+pContentLength+",目前已上传了:"+pBytesRend);
}
});
//将请求传入解析器,对请求进行解析
List<FileItem> list = upload.parseRequest(request);
//迭代list集合,得到每个输入项的数据
for (FileItem item : list) {
if (item.isFormField()) {
//普通输入项
String inputName = item.getFieldName();
String inputValue = item.getString("UTF-8");
System.out.println(inputName + ":" + inputValue);
} else {
//上传输入项
String fileName = item.getName();
if (!fileName.equals("")) {
fileName = fileName.substring(fileName
.lastIndexOf("\\") + 1);
//获取扩展名
/*String ext=fileName.substring(fileName.lastIndexOf(".")+1);
if(!fileType.contains(ext)){
request.setAttribute("message", "文件类型只能是txt,jpg,bmp");
request.getRequestDispatcher("/message.jsp").forward(request, response);
return;
}*/
String saveName=this.generateFileName(fileName);
InputStream in = item.getInputStream();
String savePath=this.getServletContext().getRealPath("WEB-INF/upload");
String savePaths = this.generateFilePath(savePath, fileName);
FileOutputStream out = new FileOutputStream(
savePaths+"\\" + saveName);
byte[] buf = new byte[1024];
int len = 0;
while ((len = in.read(buf)) > 0) {
out.write(buf, 0, len);
}
in.close();
out.close();
item.delete();
}
}
request.setAttribute("message", "上传成功");
}
}catch (FileUploadBase.FileSizeLimitExceededException e) {
request.setAttribute("message", "文件大小不能超过1M");
}
catch (Exception e) {
e.printStackTrace();
request.setAttribute("message", "上传失败");
}
request.getRequestDispatcher("/message.jsp").forward(request, response);
}
public String generateFileName(String filename){
return UUID.randomUUID().toString()+"_"+filename;
}
public String generateFilePath(String path,String filename){
int dir1 =filename.hashCode()& 0xf;
int dir2 =(filename.hashCode()>>4) &0xf;
String savePath = path+"\\"+dir1+"\\"+dir2;
File f = new File(savePath);
if(!f.exists()){
f.mkdirs();
}
return savePath;
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
}
}
实现下载的servlet,显示文件列表------------------------
package com.hbsi.servlet;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class ListFileServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
//得到上传文件的文件夹
String savepath=this.getServletContext().getRealPath("/WEB-INF/upload");
Map map=new HashMap();
listFiles(new File(savepath),map);
request.setAttribute("map",map);
request.getRequestDispatcher("/listfile.jsp").forward(request, response);
}
private void listFiles(File file,Map map){
if(file.isFile()){
String uuidname=file.getName();
String realname=uuidname.substring(uuidname.indexOf("_")+1);
map.put(uuidname,realname);
}else{
File[] files=file.listFiles();
for(File f:files){
listFiles(f,map);
}
}
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
}
}
下载的文件jsp页面--------------------------
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<!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 var="url" value="/DownloadServlet">
<c:param name="filename" value="${me.key}"></c:param>
</c:url>
文件名: ${me.value}<a href="${url}">下载</a>
<br>
</c:forEach>
</body>
</html>
处理下载请求的servlet-----------------
package com.hbsi.servlet;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URLEncoder;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class DownloadServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String filename=request.getParameter("filename");
filename=new String(filename.getBytes("iso8859-1"), "UTF-8");
//找到文件所在文件夹位置
// String savepath=this.getFileSavePath(filename);//现在的文件名是uuid的
String savepath = this.getFileSavePath(this.getRealName(filename));//现在的文件名是uuid的
File f=new File(savepath+"\\"+filename);
if(!f.exists()){
request.setAttribute("message","你下载的资源不存在");
request.getRequestDispatcher("/message.jsp").forward(request, response);
}
response.setHeader("content-disposition","attachment;filename="+URLEncoder.encode(this.getRealName(filename),"UTF-8"));
FileInputStream in = new FileInputStream(f);
byte[] buf = new byte[1024];
int len=0;
OutputStream out = response.getOutputStream();
while((len=in.read(buf))>0){
out.write(buf,0,len);
}
in.close();
}
public String getFileSavePath(String filename){
int dir1 = filename.hashCode()&0xf;
int dir2 = (filename.hashCode()>>4)&0xf;
String savepath = this.getServletContext().getRealPath("/WEB-INF/upload")+"\\"+dir1+"\\"+dir2;
return savepath;
}
public String getRealName(String filename){
String realName=filename.substring(filename.indexOf("_")+1);
return realName;
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
}
}
显示上传下载成功与否的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 'message.jsp' starting page</title>
</head>
<body>
${message}
</body>
</html>
- 完成文件上传下载功能案例
- 文件上传下载案例
- FTP上传下载文件案例详解
- FTP上传下载文件案例详解
- JavaWeb_文件上传下载_fileupload案例
- jsp实现文件上传下载功能
- 文件上传下载功能的实现
- Flask 实现文件上传下载功能
- Java实现文件上传下载功能
- java实现文件上传下载功能
- java ssh mysql实现文件上传下载功能
- JavaWeb实现文件上传下载功能实例解析
- JavaWeb实现文件上传下载功能实例解析
- JavaWeb实现文件上传下载功能实例解析
- JavaWeb实现文件上传下载功能实例解析
- JavaWeb实现文件上传下载功能实例解析
- SpringBoot实现文件上传下载的功能
- JavaWeb实现文件上传下载功能实例解析
- ios 后台无限运行
- 黑马程序员_java 多线程笔记
- Android 开机自启动程序
- UML类图几种关系的总结
- 嵌入式系统根文件系统的制作和移植
- 完成文件上传下载功能案例
- 代理模式
- Windows上的IE使用layout布局概念来控制元素的尺寸和定位。
- 面向对象设计的原则------接口隔离原则
- 阿里腾讯大战前夜:决战2013,决战移动电商!
- eclipse集成spring 并支持hibernate
- SSD 扫盲
- 数据结构之线段树
- UNIX网络编程 头文件找不到apue.h 的解决方法