<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <title>My JSP 'downloadurlpicture.jsp' starting page</title> <meta http-equiv="pragma" content="no-cache"> <meta http-equiv="cache-control" content="no-cache"> <meta http-equiv="expires" content="0"> <meta http-equiv="keywords" content="keyword1,keyword2,keyword3"> <meta http-equiv="description" content="This is my page"> <!-- <link rel="stylesheet" type="text/css" href="styles.css" mce_href="styles.css"> --> </head> <body> <% //下载网络文件 int bytesum = 0 ; int byteread = 0 ; //链接网络文件 String urlStr = request.getParameter("url"); URL url = new URL(urlStr); OutputStream os = null; String fileName = urlStr.substring(urlStr.lastIndexOf("/")+1,urlStr.length()); try { URLConnection conn = url.openConnection(); InputStream inStream = conn.getInputStream(); response.reset(); //如果要报这个异常(java.lang.IllegalStateException: getOutputStream() has already been called for this response),请把下面注释的代码启用 //out.clear(); //out=pageContext.pushBody(); //设置输出的格式,以附件的方式输出,不用用浏览器打开 response.addHeader("Content-Disposition", "attachment;filename=" + new String(fileName)); os = new BufferedOutputStream(response.getOutputStream()); response.setContentType("application/octet-stream"); byte[] buffer = new byte[1204]; while((byteread = inStream.read(buffer)) != -1 ) { bytesum += byteread; os.write(buffer,0,byteread); } } catch(Exception e) { e.printStackTrace(); } finally { os.flush(); os.close(); } %> </body> </html>