文件下载

		String filePath = wenjianService.getlujing(attachId);
		String fileName= wenjianService.getwenjianmingchengPathName(attachId);

		//下载根据文件的名称和文件路径,这些路径和名称是在一个单独的表中存在,用来单独管理这些文件
		DownloadUtil.down(request, response, fileName, filePath);
		
		

		//下载的Java文件
		public static void down(HttpServletRequest request, HttpServletResponse response
			,String filename,String filepath) throws Exception{
	 	
		//response.setContentType("application/x-msdownload");
		response.setContentType(" application/x-xls;charset=uft-8");
		response.setContentType("application/octet-stream");
	 	response.setHeader("Content-disposition","attachment; filename=" + URLEncoder.encode(filename,"utf-8")); 
		
	 	java.io.FileInputStream in = null;     
	 	java.io.BufferedInputStream binpu = null;  
	 	java.io.BufferedOutputStream bout = null; 
	 	   
	 	OutputStream output = null;
		output = response.getOutputStream();
		File file = new File(filepath);
		if(file.isDirectory()){//如果传入的是文件的目录,则添加文件名称
			filepath+= filename;
		}
		if(filepath.startsWith("ftp://"))//如果是ftp,则用FTP下载
		{
			FTPHelper ftp = new FTPHelper();
			String serverFile = ftp.parseFTPAddress(filepath);
	       	ftp.get(serverFile, output);
	        output.flush();	
	        
		}else{
			FileInputStream fis = null;
			try{
				
				in = new java.io.FileInputStream(filepath);     
			    binpu = new java.io.BufferedInputStream(in);  
			    bout = new java.io.BufferedOutputStream(response.getOutputStream());         
			    byte[] b = new byte[1024];   
			    
				int i = 0;
			    while((i = binpu.read(b,0,b.length)) > 0){     
			        bout.write(b, 0, i);     
			    }         
			    bout.flush();   
			    //要加以下两句话,否则会报错      
			    response.flushBuffer();  
			}catch(Exception e){
				e.printStackTrace();
		 	}
			finally{
				if(fis != null){
					fis.close();
		 	  		fis = null;
		 	  	}			
		 	}
		}
		if(output != null){
			output.close();
			output = null;
		}

你可能感兴趣的:(下载文件)