标签:
java下载指定地址的文件
1 package com.test; 2 3 import java.io.FileNotFoundException; 4 import java.io.FileOutputStream; 5 import java.io.IOException; 6 import java.io.InputStream; 7 import java.net.URL; 8 import java.net.URLConnection; 9 import java.text.DecimalFormat; 10 import java.text.SimpleDateFormat; 11 import java.util.Date; 12 13 public class TestFile { 14 15 public static void main(String[] args) { 16 try { 17 int byteSum = 0;//已下载字节数 18 int byteRead = 0;//读取字节数 19 int byteCount = 0;//总字节数 20 String filePath = "http://123.157.149.169/down/37f3e48bf5a412ea27f01be2b5e00a4c-18173940/%5BROSI%5D2013.09.22%20NO.659%5B25%2B1P%5D.rar?cts=223A167A86A3&ctp=223A167A86A3&ctt=1379946470&limit=3&spd=0&ctk=0d4b4e4b39e9b9a1c8d4104e07a79c90&chk=37f3e48bf5a412ea27f01be2b5e00a4c-18173940&mtd=1"; 21 URL url = new URL(filePath); 22 URLConnection conn = url.openConnection(); 23 //获取文件名 24 String path = url.getPath(); 25 Date d = new Date(); 26 SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmssms"); 27 String fileName = sdf.format(d) + path.substring(path.lastIndexOf(".")); 28 System.out.println("文件名称:"+ fileName ); 29 //获取总字节数 30 byteCount = conn.getContentLength(); 31 double len = Double.parseDouble(byteCount+"")/(1024*1024); 32 DecimalFormat df = new DecimalFormat("0.##"); 33 System.out.println("文件大小:" + df.format(len) + "MB"); 34 35 InputStream inStream = conn.getInputStream(); 36 FileOutputStream fs = new FileOutputStream("E:/"+fileName); 37 byte[] buffer = new byte[1204]; 38 System.out.println("文件开始下载...."); 39 while (( byteRead = inStream.read(buffer)) != -1) { 40 byteSum += byteRead; 41 int num = byteSum*100/Integer.parseInt(byteCount+""); 42 System.out.println("已下载"+ num +"%...."); 43 fs.write(buffer, 0, byteRead); 44 } 45 System.out.println("文件下载完成!"); 46 } catch (FileNotFoundException e) { 47 e.printStackTrace(); 48 } catch (IOException e) { 49 e.printStackTrace(); 50 } 51 } 52 }
java如何将导出的excel下载到客户端
1 import java.io.IOException; 2 import java.io.PrintWriter; 3 4 import javax.servlet.ServletException; 5 import javax.servlet.ServletOutputStream; 6 import javax.servlet.http.HttpServlet; 7 import javax.servlet.http.HttpServletRequest; 8 import javax.servlet.http.HttpServletResponse; 9 /** 10 * 利用Servlet导出Excel 11 * @author CHUNBIN 12 * 13 */ 14 public class ExportExcelServlet extends HttpServlet { 15 16 public void doGet(HttpServletRequest request, HttpServletResponse response) 17 throws ServletException, IOException { 18 doPost(request, response); 19 } 20 21 public void doPost(HttpServletRequest request, HttpServletResponse response) 22 throws ServletException, IOException { 23 request.setCharacterEncoding("UTF-8");//设置request的编码方式,防止中文乱码 24 String fileName ="导出数据";//设置导出的文件名称 25 StringBuffer sb = new StringBuffer(request.getParameter("tableInfo"));//将表格信息放入内存 26 String contentType = "application/vnd.ms-excel";//定义导出文件的格式的字符串 27 String recommendedName = new String(fileName.getBytes(),"iso_8859_1");//设置文件名称的编码格式 28 response.setContentType(contentType);//设置导出文件格式 29 response.setHeader("Content-Disposition", "attachment; filename=" + recommendedName + "\"");// 30 response.resetBuffer(); 31 //利用输出输入流导出文件 32 ServletOutputStream sos = response.getOutputStream(); 33 sos.write(sb.toString().getBytes()); 34 sos.flush(); 35 sos.close(); 36 } 37 }
1 <%@ page language="java" contentType="text/html; charset=UTF-8" 2 pageEncoding="UTF-8"%> 3 <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> 4 <html> 5 <head> 6 <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> 7 <title>导出Excel</title> 8 <script type="text/javascript"> 9 function test(){ 10 document.getElementById("tableInfo").value=document.getElementById("table").innerHTML; 11 } 12 </script> 13 <style> 14 body{font-family:宋体;font-size:11pt} 15 </style> 16 </head> 17 <body> 18 <form action="<%=request.getContextPath()%>/servlet/ExportExcelServlet" method="post"> 19 <span id="table"> 20 <table bgcolor="#EEECF2" bordercolor="#A3B2CC" border="1" cellspacing="0"> 21 <tr><th>学号</th><th>姓名</th><th>科目</th><th>分数</th></tr> 22 <tr><td>10001</td><td>赵二</td><td>高数</td><td>82</td></tr> 23 <tr><td>10002</td><td>张三</td><td>高数</td><td>94</td></tr> 24 <tr><td>10001</td><td>赵二</td><td>线数</td><td>77</td></tr> 25 <tr><td>10002</td><td>张三</td><td>线数</td><td>61</td></tr> 26 </table> 27 </span> 28 <input type="submit" name="Excel" value="导出表格" onclick="test()"/> 29 <input type="hidden" id="tableInfo" name="tableInfo" value=""/> 30 </form> 31 </body> 32 </html>
upload_json.jsp
1 <%@ page language="java" contentType="text/html; charset=UTF-8" 2 pageEncoding="UTF-8"%> 3 <%@ page import="java.util.*,java.io.*"%> 4 <%@ page import="java.text.SimpleDateFormat"%> 5 <%@ page import="org.apache.commons.fileupload.*"%> 6 <%@ page import="org.apache.commons.fileupload.disk.*"%> 7 <%@ page import="org.apache.commons.fileupload.servlet.*"%> 8 <%@ page import="com.opensymphony.xwork2.ActionContext"%> 9 <%@ page 10 import="org.apache.struts2.dispatcher.multipart.MultiPartRequestWrapper"%> 11 <%@ page import="org.json.simple.*"%> 12 <% 13 //文件保存目录路径 14 String savePath = pageContext.getServletContext().getRealPath("/") 15 + "kindeditor/attached/"; 16 17 //文件保存目录URL 18 String saveUrl = request.getContextPath() + "/kindeditor/attached/"; 19 20 //定义允许上传的文件扩展名 21 HashMap<String, String> extMap = new HashMap<String, String>(); 22 extMap.put("image", "gif,jpg,jpeg,png,bmp"); 23 extMap.put("flash", "swf,flv"); 24 extMap.put("media", 25 "swf,flv,mp3,wav,wma,wmv,mid,avi,mpg,asf,rm,rmvb"); 26 extMap.put("file", 27 "doc,docx,xls,xlsx,ppt,htm,html,txt,zip,rar,gz,bz2"); 28 29 //最大文件大小 30 long maxSize = 1000000; 31 32 response.setContentType("text/html; charset=UTF-8"); 33 34 if (!ServletFileUpload.isMultipartContent(request)) { 35 out.println(getError("请选择文件。")); 36 return; 37 } 38 //检查目录 39 File uploadDir = new File(savePath); 40 if (!uploadDir.isDirectory()) { 41 out.println(getError("上传目录不存在。")); 42 return; 43 } 44 //检查目录写权限 45 if (!uploadDir.canWrite()) { 46 out.println(getError("上传目录没有写权限。")); 47 return; 48 } 49 50 String dirName = request.getParameter("dir"); 51 if (dirName == null) { 52 dirName = "image"; 53 } 54 if (!extMap.containsKey(dirName)) { 55 out.println(getError("目录名不正确。")); 56 return; 57 } 58 //创建文件夹 59 savePath += dirName + "/"; 60 saveUrl += dirName + "/"; 61 File saveDirFile = new File(savePath); 62 if (!saveDirFile.exists()) { 63 saveDirFile.mkdirs(); 64 } 65 SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd"); 66 String ymd = sdf.format(new Date()); 67 savePath += ymd + "/"; 68 saveUrl += ymd + "/"; 69 File dirFile = new File(savePath); 70 if (!dirFile.exists()) { 71 dirFile.mkdirs(); 72 } 73 MultiPartRequestWrapper wrapper = (MultiPartRequestWrapper) request; 74 75 //获得上传的文件名 76 String fileName = wrapper.getFileNames("imgFile")[0];//imgFile,imgFile,imgFile 77 78 //获得文件过滤器 79 File file = wrapper.getFiles("imgFile")[0]; 80 81 //检查扩展名 82 String fileExt = fileName.substring(fileName.lastIndexOf(".") + 1) 83 .toLowerCase(); 84 if (!Arrays.<String> asList(extMap.get(dirName).split(",")) 85 .contains(fileExt)) { 86 out.println(getError("上传文件扩展名是不允许的扩展名。\n只允许" 87 + extMap.get(dirName) + "格式。")); 88 return; 89 } 90 91 //检查文件大小 92 if (file.length() > maxSize) { 93 out.println(getError("上传文件大小超过限制。")); 94 return; 95 } 96 97 //重构上传图片的名称 98 SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmss"); 99 String newImgName = df.format(new Date()) + "_" 100 + new Random().nextInt(1000) + "." + fileExt; 101 byte[] buffer = new byte[1024]; 102 103 //获取文件输出流 104 FileOutputStream fos = new FileOutputStream(savePath + "/" 105 + newImgName); 106 107 //System.out.println("########" + saveUrl + "@@"+ newImgName); 108 //获取内存中当前文件输入流 109 InputStream in = new FileInputStream(file); 110 try { 111 int num = 0; 112 while ((num = in.read(buffer)) > 0) { 113 fos.write(buffer, 0, num); 114 } 115 } catch (Exception e) { 116 e.printStackTrace(System.err); 117 } finally { 118 in.close(); 119 fos.close(); 120 } 121 122 JSONObject obj = new JSONObject(); 123 obj.put("error", 0); 124 obj.put("url", saveUrl + newImgName); 125 out.println(obj.toJSONString()); 126 %> 127 <%!private String getError(String message) { 128 JSONObject obj = new JSONObject(); 129 obj.put("error", 1); 130 obj.put("message", message); 131 return obj.toJSONString(); 132 }%>
struts下载文件配置
1 public String download() throws Exception { 2 uploadFileName="中文.jpg"; 3 downStream = ServletActionContext.getServletContext() 4 .getResourceAsStream(inputPath); 5 return SUCCESS; 6 } 7 8 <action name="download" class="upload.DownloadAction" method="download"> 9 <!-- 指定被下载资源的位置 --> 10 <param name="inputPath">\download\中文.jpg</param> 11 <!-- 配置结果类型为stream的结果 --> 12 <result name="success" type="stream"> 13 <!-- 指定返回下载文件的InputStream --> 14 <param name="inputName">downStream</param> 15 <!-- 指定下载文件的文件类型 --> 16 <param name="contentType">image/jpg</param> 17 <param name="contentDisposition">attachment;filename=${uploadFileName}</param> 18 <!-- 指定下载文件的缓冲大小 --> 19 <param name="bufferSize">4096</param> 20 </result> 21 <result name="input">/upload.jsp 22 </result> 23 </action> 24 25 页面 26 <a href="download.action">下载包含中文文件名的文件</a>
1 /这一段代码我也是不知道是哪里的 先放上去 以后再看吧 2 3 public String executeCommandUDownload(ActionContext context)throws Exception{ 4 HttpServletResponse response = context.getResponse(); 5 response.setCharacterEncoding("UTF-8"); 6 boolean isOnLine = false; 7 String fileName = context.getRequest().getParameter("fileName"); 8 9 Connection con = null; 10 HttpServletRequest request = context.getRequest(); 11 String filePath = null; 12 BufferedInputStream buffer=null; 13 OutputStream out=null; 14 try 15 { 16 con = this.getConnection(context); 17 if("".equals(fileName) || fileName == null){ 18 FileInfoBean bean = new FileInfoBean(); 19 fileName = bean.findName(con, id); 20 21 } 22 23 24 25 File f = new File(filePath); 26 //检查该文件是否存在 27 if(!f.exists()){ 28 response.sendError(404,"File not found!"); 29 return "File not found!"; 30 } 31 buffer = new BufferedInputStream(new FileInputStream(f)); 32 byte[] buf = new byte[1024]; 33 int len = 0; 34 35 response.reset(); //非常重要 36 if(isOnLine){ //在线打开方式 37 URL u = new URL("file:///"+filePath); 38 response.setContentType(u.openConnection().getContentType()); 39 response.setHeader("Content-Disposition", "inline; filename="+(f.getName()).getBytes("gbk")); 40 //文件名应该编码成UTF-8 41 } 42 else{ //纯下载方式 43 44 response.setContentType("application/x-msdownload"); 45 46 response.setHeader("Content-Disposition", "attachment; filename=" + java.net.URLEncoder.encode(f.getName(),"UTF-8")); 47 48 } 49 out = response.getOutputStream(); 50 while((len = buffer.read(buf)) >0) 51 out.write(buf,0,len); 52 }catch(Throwable e) 53 { 54 e.printStackTrace(); 55 }finally 56 { 57 try 58 { 59 buffer.close(); 60 out.close(); 61 }catch(Throwable e) 62 { 63 e.printStackTrace(); 64 } 65 } 66 return ""; 67 }
标签:
原文地址:http://www.cnblogs.com/cangqiongbingchen/p/4530776.html