System.out.println(this.getServletContext().getContextPath()); //服务器中的只能是web应用
System.out.println(this.getServletContext().getRealPath("/WEB-INF/upload")); //服务器中的
System.out.println(request.getServletPath()+"/WEB-INF/upload"); //浏览器中的
/heima_day15
E:\apache-tomcat-7.0.0\webapps\heima_day15\WEB-INF\upload
/test/WEB-INF/upload
1.response.setHeader("Content-disposition", "attachment;filename="+URLEncoder.encode(中文的名字,"utf-8")); //这个如果是要中文的文件名字的话就要加URLEncoder.encode。。
URLEncoder.encode(String)是对url中的中文参数经行编码的,可以解决乱码的问题。
2.response.setContentType(this.getServletContext().getMimeType(fSource.getRealname())); //文件的类型
InputStream in=new FileInputStream(new File(this.getServletContext().getRealPath(fSource.getSavepath()),fSource.getUuidname()));
OutputStream out=response.getOutputStream();
IOUtils.in2out(in, out);
IOUtils.close(in, out);
上传:
//1. 拿到DiskFileItemFactory
DiskFileItemFactory dItem=new DiskFileItemFactory();
dItem.setSizeThreshold(1024*1024*2);
dItem.setRepository(new File(this.getServletContext().getRealPath("/WEB-INF/upload")));
//2.
ServletFileUpload sUpload=new ServletFileUpload(dItem);
sUpload.setFileSizeMax(1024*1024*100);
sUpload.setSizeMax(1024*1024*500);
sUpload.setHeaderEncoding("utf-8");
//3
List<FileItem> list= sUpload.parseRequest(request);
for(FileItem fItem:list){
if(fItem.isFormField()){ // 普通字段
String name=fItem.getFieldName();
String value=fItem.getString("utf-8");
map.put(name, value);
}else {
String realname= fItem.getName();
realname= realname.substring(realname.lastIndexOf("\\")+1);
map.put("realname", realname);
String name= UUID.randomUUID().toString()+"_"+realname;
map.put("uuidname", name);
InputStream in= fItem.getInputStream(); //拿到上传文件的流
String code=Integer.toHexString( name.hashCode());
String path=this.getServletContext().getRealPath("/WEB-INF/upload");
char[] chs=code.toCharArray();
String savepath="/WEB-INF/upload";
for(char s:chs){
path+="/"+s;
savepath+="/"+s;
}
new File(path).mkdirs();
map.put("savepath", savepath);
FileOutputStream fout=new FileOutputStream(new File(path,name));
IOUtils.in2out(in, fout);
IOUtils.close(in, fout);
fItem.delete(); // 删除临时文件