简单的下载例子

       前两天看代码,有一个下载的例子,我觉得写得挺全面的,所以就传上来,以后再需要些这样的例子就直接拿走了:

public void downLoad(@Read(key="url")String url){
		//获取参数
		int npos = url.lastIndexOf("/");

		//获取文件名
		String filename = url.substring(npos+1);
		int npos2 = filename.indexOf(".");

		//获取文件类型
		String filetype = filename.substring(npos2);
		HttpServletResponse response=this.getResponse();
		if (filetype.equalsIgnoreCase("doc")) { //doc文档
		    response.setHeader("Content-Type","application/msword");
		}
		else if (filetype.equalsIgnoreCase("xls")) { //xls文档
		    response.setHeader("Content-Type","application/msexcel");
		}
		else if (filetype.equalsIgnoreCase("ppt")) { //ppt文档
		    response.setHeader("Content-Type","application/mspowerpoint");
		}
		else if (filetype.equalsIgnoreCase("pdf")) { //pdf文档
		    response.setHeader("Content-Type","application/pdf");
		}
		else if (filetype.equalsIgnoreCase("zip")) { //zip文档
		    response.setHeader("Content-Type","application/zip");
		}
		else if (filetype.equalsIgnoreCase("rar")) { //rar文档
		    response.setHeader("Content-Type","application/rar");
		}
		else if (filetype.equalsIgnoreCase("jpg")) { //jpg图片
		    response.setHeader("Content-Type","image/JPEG");
		}
else if (filetype.equalsIgnoreCase("txt")) { //txt文档
		    response.setHeader("Content-Type","application/txt");
		}

		else {
		    response.setHeader("Content-Type","application/x-msdownload");
		}
		PrintWriter out;
		try {
			OutputStream outputStream = response.getOutputStream();
			//读取文件来源
			//URL url_url = new URL(url);
			//HttpURLConnection connection = (HttpURLConnection) url_url.openConnection();
			//connection.connect();
			String rootPath = this.getServlet().getServletContext()
					.getRealPath("/");
			String path = rootPath + url;
			//String path=rootPath+"Modules/downloads/agentcontract/space.txt";
			System.out.println(path);
			InputStream inputStream = new FileInputStream(path);
			;
			response.setHeader("Pragma", "no-cache");
			//response.setContentType("application/x-download");
			//response.setHeader("Location",url);
			response.setHeader("Content-Disposition", "attachment; filename="
					+ filename);
			//response.setContentLength(filelength);
			byte[] buffer = new byte[1024];
			int i = -1;
			while ((i = inputStream.read(buffer)) != -1) {
				outputStream.write(buffer, 0, i);
			}
			outputStream.flush();
			outputStream.close();
			inputStream.close();
			outputStream = null;
			out = response.getWriter();
			out.flush();
			//out = pageContext.pushBody();
		} catch (Exception e) {
			// TODO: handle exception
		}


	}

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