首先引入2个jar
![](http://images2017.cnblogs.com/blog/1128666/201711/1128666-20171101145630498-2084371020.png) package uploaddownload; import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.sql.Savepoint;
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.ProgressListener;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
/**
*
* @ClassName UploadBoost
* @Description TODO(这里用一句话描述这个类的作用)
* @Author pengzh humi
* @Date 2017年11月1日 上午10:38:36
*/
public class UploadBoost extends HttpServlet{ private static final long serialVersionUID = 1L; @Override
public void init() throws ServletException {
System.out.println("UploadBoost init ...");
}
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
System.out.println("DO Get method ...");
String saveFile = this.getServletContext().getRealPath("/WEB-INF/upload");
String tempPath = this.getServletContext().getRealPath("/WEB-INF/temp");
File tempFile = new File(tempPath);
if(!tempFile.exists()){
tempFile.mkdir();
}
//消息提示
String message="";
InputStream in =null;
FileOutputStream out = null; try {
DiskFileItemFactory factory = new DiskFileItemFactory();
factory.setSizeThreshold(1024*1024*5);//5k缓存
factory.setRepository(tempFile);//临时保存路径
ServletFileUpload upload = new ServletFileUpload(factory);//创建文件解析器
upload.setProgressListener(new ProgressListener() {//上传进度
public void update(long finished, long total, int rate) {
// TODO Auto-generated method stub
System.out.println("文件上传进度"+finished+"/"+total+"|"+Math.floor((double)(finished*100/total))+"% rate="+rate);
}
});
upload.setHeaderEncoding("utf-8");//解决文件名乱码
if(!ServletFileUpload.isMultipartContent(req)){
message = "非媒体文件上传";
return;
}
upload.setFileSizeMax(1024*1024*5);//设置单个文件上传最大为5M
upload.setSizeMax(1024*1024*10);//设置上传文件总量最大值为5M List<FileItem> fileList = upload.parseRequest(req);
for (FileItem item : fileList) {
if(item.isFormField()){
System.out.println("表单数据:name="+item.getFieldName()+" value="+item.getString("utf-8"));
}else{
String fileName =item.getName();
if(fileName==null||fileName.trim().equals("")){
continue;
}
System.out.println("上传的文件名:"+fileName);
fileName = getFileName(fileName.substring(fileName.lastIndexOf("\\")+1));//得到唯一文件名
String fileExtName=fileName.substring(fileName.lastIndexOf(".")+1);//得到后缀名
String dir = getPaht(fileName, saveFile);
System.out.println("唯一文件名:"+fileName+"\n文件扩展名"+fileExtName+"\n保存路径名:"+saveFile+"\n哈希路径:"+dir);
in = item.getInputStream();
out = new FileOutputStream(dir+"\\"+fileName);
byte[] buff= new byte[1024];//字节流 1k缓冲
int length=0;//文件标记位
while((length=in.read(buff, 0, length))>0){
out.write(buff, 0, length);
}
message="文件上传成功";
}
}
}catch (FileUploadBase.FileSizeLimitExceededException e) {
System.out.println("上传失败 "+e.getMessage());
message="上传失败 "+e.getMessage();
}catch (FileUploadBase.SizeLimitExceededException e) {
System.out.println("上传失败 "+e.getMessage());
message="上传失败 "+e.getMessage();
}catch (Exception e) {
System.out.println("上传失败 "+e.getMessage());
message="上传失败 "+e.getMessage();
}finally{
//关闭流 并置空 让JVM去回收
out.close();out=null;
in.close();in=null;
//消息提示
System.out.println("message="+message);
req.setAttribute("message", message);
req.getRequestDispatcher("/message.jsp").forward(req, resp);
} } @Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
System.out.println("Do Post method ...");
doGet(req, resp);
}
/**
*
* @param name
* @return 唯一文件名
*/
public String getFileName(String name){
return UUID.randomUUID().toString()+"_"+name;
}
/**
*
* @param name
* @param path
* @return 得到哈希路径
*/
public String getPaht(String name,String path){
int hashcode = name.hashCode();
int dir1 = hashcode&0xf;
int dir2 = dir1>>4;
// System.out.println("hashcode="+hashcode+"\ndir1="+dir1+"\ndir2="+dir2);
String dir = path +"\\"+dir1+"\\"+dir2;
File file = new File(dir);
if(!file.exists()){
file.mkdirs();
// System.out.println("file==="+file+" "+file.toURI());
}
return dir;
}
} =============================================================== package uploaddownload; import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
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;
/**
*
* @ClassName DownLoadServlet
* @Description 文件下载
* @Author pengzh humi
* @Date 2017年11月2日 下午8:10:20
*/
public class DownLoadServlet extends HttpServlet{ private static final long serialVersionUID = 1L; @Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
String realPaht= this.getServletContext().getRealPath("/WEB-INF/upload");
String fileName =req.getParameter("filename");
String filePath =findFileBySavePath(fileName, realPaht);
File file = new File(filePath+"\\"+fileName);//得到需要下载的文件
System.out.println("文件下载 DownLoadServlet 路径"+filePath+"\\"+fileName);
if(!file.exists()){
req.setAttribute("message", "你要下载的文件已删除");
req.getRequestDispatcher("/message.jsp").forward(req, resp);
return;
}
fileName = fileName.substring(fileName.lastIndexOf('_')+1);
//设置响应头,控制浏览器下载该文件
resp.setHeader("content-disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));
OutputStream out=resp.getOutputStream();
FileInputStream in = new FileInputStream(file);
int len =0;
byte[] buff= new byte[1024];
System.out.println("将下载 DownLoadServlet: "+fileName);
while((len=in.read(buff))>0){
out.write(buff, 0, len);
}
} @Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
doGet(req, resp);
}
/**
*
* @param fileName 文件名
* @param savePath 下载后保存的路径
* @return
*/
public String findFileBySavePath(String fileName,String savePath){
int hashCode = fileName.hashCode();
int dir1 = hashCode&0xf;
int dir2 = dir1>>4;
String dir = savePath+"\\"+dir1+"\\"+dir2;
System.out.println("保存目录处理:dir1="+dir1+" dir2="+dir2+" dir="+dir);
File file = new File(dir);
if(!file.exists()){
file.mkdirs();
}
return dir;
}
}

java 文件上传 下载 总结的更多相关文章

  1. 2013第38周日Java文件上传下载收集思考

    2013第38周日Java文件上传&下载收集思考 感觉文件上传及下载操作很常用,之前简单搜集过一些东西,没有及时学习总结,现在基本没啥印象了,今天就再次学习下,记录下自己目前知识背景下对该类问 ...

  2. Java文件上传下载原理

    文件上传下载原理 在TCP/IP中,最早出现的文件上传机制是FTP.它是将文件由客户端发送到服务器的标准机制. 但是在jsp编程中不能使用FTP方法来上传文件,这是由jsp运行机制所决定的 文件上传原 ...

  3. java文件上传下载

    文件上传首先要引入两个核心包 commons-fileupload-1.2.1.jar commons-io-1.4.jar 下面是对文件上传和下载的一些代码做的一个简单封装,可以方便以后直接使用[使 ...

  4. java文件上传下载组件

    需求: 支持大文件批量上传(20G)和下载,同时需要保证上传期间用户电脑不出现卡死等体验: 内网百兆网络上传速度为12MB/S 服务器内存占用低 支持文件夹上传,文件夹中的文件数量达到1万个以上,且包 ...

  5. java 文件上传下载

    翻新十年前的老项目,文件上传改为调用接口方式,记录一下子~~~ java后台代码: //取配置文件中的上传目录 @Value("${uploadPath}") String pat ...

  6. java文件上传下载解决方案

    javaweb上传文件 上传文件的jsp中的部分 上传文件同样可以使用form表单向后端发请求,也可以使用 ajax向后端发请求 1.通过form表单向后端发送请求 <form id=" ...

  7. [Java] 文件上传下载项目(详细注释)

    先上代码,最上方注释是文件名称(运行时要用到) FTServer.java /* FTServer.java */ import java.util.*; import java.io.*; publ ...

  8. java文件上传下载 使用SmartUpload组件实现

    使用SmartUpload组件实现(下载jsmartcom_zh_CN.jar) 2017-11-07 1.在WebRoot创建以下文件夹,css存放样式文件(css文件直接拷贝进去),images存 ...

  9. [java]文件上传下载删除与图片预览

    图片预览 @GetMapping("/image") @ResponseBody public Result image(@RequestParam("imageName ...

随机推荐

  1. 详解VMware 虚拟机中添加新硬盘的方法

    一.VMware新增磁盘的设置步骤 (建议:在设置虚拟的时候,不要运行虚拟机的系统,不然添加了新的虚拟磁盘则要重启虚拟机) 1.选择“VM”----“设置”并打开,将光标定位在“硬盘(SCSI)”这一 ...

  2. jquery iframe取得元素与自适应高度

    总结一下iframe在jquery中怎么操作的,下面我来给各位介绍jquery 获取iframe子/父页面的元素及iframe在jquery高度自适应实现方法,各位朋友可参考. jquery方法: 在 ...

  3. python:python2与python3共存时,pip冲突,提示Fatal error in launcher: Unable to create process using '"d:\python27\python2.exe" "D:\Python27\Scripts\pip2.exe" '

    问题背景: 机器上同时装了python2.和python3后,导致只能用pip3了,使用pip2时提示:Fatal error in launcher: Unable to create proces ...

  4. 神经网络与机器学习第3版学习笔记-第1章 Rosenblatt感知器

    神经网络与机器学习第3版学习笔记 -初学者的笔记,记录花时间思考的各种疑惑 本文主要阐述该书在数学推导上一笔带过的地方.参考学习,在流畅理解书本内容的同时,还能温顾学过的数学知识,达到事半功倍的效果. ...

  5. 2019-10-24 李宗盛 spss作业

    3.1数据排序.  在统计分析时最初的变量.  可能不符合统计分析的要求,需要用户对目标数据进行整理,来符合分析方法个案排序.数据——个案排序.排序依据,排序顺序,变量排序 数据——变量排序 变量视图 ...

  6. 使用eclipse插件mybatis generator来自动生成实体类及映射文件

    <?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE generatorConfiguratio ...

  7. Java使用icepdf转高清图片

    <dependency> <groupId>org.icepdf.os</groupId> <artifactId>icepdf-core</ar ...

  8. [转帖]英特尔首次使用其3D堆叠架构演示Lakefield芯片设计

    英特尔首次使用其3D堆叠架构演示Lakefield芯片设计 http://www.chinapeace.org.cn/keji/201904/2812749.html 这段时间学习最大的收获: . 发 ...

  9. C++经典类库

    现实中,C++的库门类繁多,解决的问题也是极其广泛,库从轻量级到重量级的都有.本文为你介绍了十一种类库,有我们常见的,也有不常见的,一起来看. C++类库介绍 再次体现了C++保持核心语言的效率同时大 ...

  10. time() 函数时间不同步问题

    1.时区设置问题 处理方法:编辑php.ini  搜索 “timezone” 改写为 PRC 时区 2.服务器时间不同步 处理方法:设置服务器时间和本地时间进行同步