1、文件的下载
在下载时首先要设置MIME类型;
(1)servlet
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
//声明MIME类型。
response.setContentType("application/x-msdownload");
//设置要上传的文件
File file=new File("e:"+File.separator+"hello.txt");
//获取上传的文件的名字
String fileName=file.getName();
//输入文件
InputStream intStream=new FileInputStream(file);
//输出文件
OutputStream out=response.getOutputStream();
//在下载时使下载的文件与上传的文件的名字一致
response.setHeader("Content-Disposition", "attachment;filename="+fileName+"");
if (!file.exists()) {
System.out.println("文件不存在");
}else{
byte[] b=new byte[1024];
int len=0;
while ((len=intStream.read(b))!=-1) {
out.write(b, 0, len);
}
}if (out!=null) {//关闭流
out.close();
}if (intStream!=null) {
intStream.close();
}
}
(2)index.html
<a href="download">下载文件</a>
2文件的上传
1)利用Tomcat3.0新特性进行多个文件上传
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
Collection<Part> part=request.getParts();
//foreach写法
/* int len=part.size();
if (len==1) {
Part part1=request.getPart("file");
String filename=getName(part1);
String path="e:"+File.separator+filename;
part1.write(path);
}else {
for (Part part2 : part) {
String filename=getName(part2);
String path="e:"+File.separator+filename;
part2.write(path);
}
}*/
//迭代器写法
Iterator<Part> iterator=part.iterator();
while (iterator.hasNext()) {
Part part2 = (Part) iterator.next();
String filename=getName(part2);
String path="e:"+File.separator+filename;
part2.write(path);
}
}
//获取上传文件的名字
public String getName(Part part){
String head=part.getHeader("Content-Disposition");
int lastindex=head.lastIndexOf("\"");
int firstindex=head.lastIndexOf("\"", lastindex-1);
String filename=head.substring(firstindex+1, lastindex);
return filename;
}
2)使用第三方框架进行多个文件进行上传
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
request.setCharacterEncoding("utf-8");
DiskFileItemFactory factory=new DiskFileItemFactory();//获得磁盘条目工厂
String path="e:"+File.separator;//上传的路径
factory.setRepository(new File(path));
factory.setSizeThreshold(1024*1024);
//高水平的API文件上传处理
ServletFileUpload fileUpload=new ServletFileUpload(factory);
List<FileItem> list;
try {
list = (List<FileItem>)fileUpload.parseRequest(request);
for (FileItem fileItem : list) {
String filename=fileItem.getName();
try {
//利用第三方框架进行上传
fileItem.write(new File(path, filename));
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
} catch (FileUploadException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}