1.8
思路:
A.文件上传实现步骤:
1.处理上传: a.创建工厂 b.创建servletFileUpload对象 c.遍历request请求 d.遍历list集合并判断,是普通表单域还是文件上传域。
2.存入导数据
B.文件下载处理:
1.方法一:直接用<A>连接到资源位置,当然这很不安全。
方法二:用二进制流进行下载。
C:国际化,理解即可
文件上传实例:
获取上传文件名称的方法
方法一
String filepath=" G:/a/b/模块划分.rar"
File file1=new File(filepath);
System.out.println("file1.getName() "+file1.getName());
方法二
String filepath=" G:/a/b/模块划分.rar"
String fileName=filepath.substring(filepath.lastIndexOf("//")+1);
System.out.println("fileName "+fileName);
限制上传文件的大小
// 利用工厂创建ServletUpLoadFIle
ServletFileUpload upload = new ServletFileUpload(fileItemFactory);
//设置上传文件的最大字节数(要求不能超过3M)
long maxSize=1024*1024*3;
upload.setFileSizeMax(maxSize);
当上传的文件超多该数值时,将抛出 FileSizeLimitExceededException
哪些类型的文件可以上传
//限制上传文件的后缀名
//获取上传文件的后缀名,如没有后缀名,不接收
//G:/a/b/模块划分.rar"
String endWith=filepath.substring(filepath.lastIndexOf(".")+1);
System.out.println("endWith "+endWith);
//private String[] allowName={"zip","jar","jpg","doc"};
if(!java.util.Arrays.asList(allowName).contains(endWith)){
throw new RuntimeException("该类型的文件不能上传!!!!");
}
文件下载流程
//获取文件路径
String filepath=request.getParameter("filepath");
//获取文件名
String filename=request.getParameter("filename");
response.setContentType("application/x-msdownload");
//处理保存文件的名字,中文乱码
response.setHeader("Content-Disposition",
"attachment;filename="+new String(filename.getBytes("gbk"),"ISO-8859-1"));
filepath=filepath+"/"+filename;
//获取要下载文件的绝对路径
filepath =this.getServletContext().getRealPath(filepath);
System.out.println("filepath "+filepath);
//读取文件的输入流
FileInputStream fis=new FileInputStream(filepath);
BufferedInputStream bis=new BufferedInputStream(fis);
//下载文件的输出流
BufferedOutputStream bos=new BufferedOutputStream(response.getOutputStream());
byte[] b=new byte[1024*200];
int len=0;
while((len=bis.read(b))!=-1){
bos.write(b, 0, len);
}
bos.close();
bis.close();