java下载指定地址的文件

 package com.test;

 import java.io.FileNotFoundException;
 import java.io.FileOutputStream;
 import java.io.IOException;
 import java.io.InputStream;
 import java.net.URL;
 import java.net.URLConnection;
 import java.text.DecimalFormat;
 import java.text.SimpleDateFormat;
 import java.util.Date;

 public class TestFile {

     public static void main(String[] args) {
         try {
             int byteSum = 0;//已下载字节数
             int byteRead = 0;//读取字节数
             int byteCount = 0;//总字节数
             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";
             URL url = new URL(filePath);
             URLConnection conn = url.openConnection();
             //获取文件名
             String path = url.getPath();
             Date d = new Date();
             SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmssms");
             String fileName = sdf.format(d) + path.substring(path.lastIndexOf("."));
             System.out.println("文件名称:"+ fileName );
             //获取总字节数
             byteCount = conn.getContentLength();
             double len = Double.parseDouble(byteCount+"")/(1024*1024);
             DecimalFormat df = new DecimalFormat("0.##");
             System.out.println("文件大小:" + df.format(len) + "MB");

             InputStream inStream = conn.getInputStream();
             FileOutputStream fs = new FileOutputStream("E:/"+fileName);
             byte[] buffer = new byte[1204];
             System.out.println("文件开始下载....");
             while (( byteRead = inStream.read(buffer)) != -1) {
                 byteSum += byteRead;
                 int num = byteSum*100/Integer.parseInt(byteCount+"");
                 System.out.println("已下载"+ num +"%....");
                 fs.write(buffer, 0, byteRead);
             }
             System.out.println("文件下载完成!");
         } catch (FileNotFoundException e) {
             e.printStackTrace();
         } catch (IOException e) {
             e.printStackTrace();
         }
     }
 }

java如何将导出的excel下载到客户端

 import java.io.IOException;
 import java.io.PrintWriter;

 import javax.servlet.ServletException;
 import javax.servlet.ServletOutputStream;
 import javax.servlet.http.HttpServlet;
 import javax.servlet.http.HttpServletRequest;
 import javax.servlet.http.HttpServletResponse;
 /**
  * 利用Servlet导出Excel
  * @author CHUNBIN
  *
  */
 public class ExportExcelServlet extends HttpServlet {

        public void doGet(HttpServletRequest request, HttpServletResponse response)
                      throws ServletException, IOException {
               doPost(request, response);
        }

        public void doPost(HttpServletRequest request, HttpServletResponse response)
                      throws ServletException, IOException {
               request.setCharacterEncoding("UTF-8");//设置request的编码方式,防止中文乱码
               String fileName ="导出数据";//设置导出的文件名称
               StringBuffer sb = new StringBuffer(request.getParameter("tableInfo"));//将表格信息放入内存
               String contentType = "application/vnd.ms-excel";//定义导出文件的格式的字符串
               String recommendedName = new String(fileName.getBytes(),"iso_8859_1");//设置文件名称的编码格式
               response.setContentType(contentType);//设置导出文件格式
               response.setHeader("Content-Disposition", "attachment; filename=" + recommendedName + "\"");//
               response.resetBuffer();
               //利用输出输入流导出文件
               ServletOutputStream sos = response.getOutputStream();
               sos.write(sb.toString().getBytes());
               sos.flush();
               sos.close();
        }
 }
 <%@ page language="java" contentType="text/html; charset=UTF-8"
     pageEncoding="UTF-8"%>
 <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
 <html>
 <head>
 <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
 <title>导出Excel</title>
 <script type="text/javascript">
     function test(){
        document.getElementById("tableInfo").value=document.getElementById("table").innerHTML;
     }
 </script>
 <style>
     body{font-family:宋体;font-size:11pt}
 </style>
 </head>
 <body>
 <form action="<%=request.getContextPath()%>/servlet/ExportExcelServlet" method="post">
     <span id="table">
     <table bgcolor="#EEECF2" bordercolor="#A3B2CC" border="1" cellspacing="0">
        <tr><th>学号</th><th>姓名</th><th>科目</th><th>分数</th></tr>
        <tr><td>10001</td><td>赵二</td><td>高数</td><td>82</td></tr>
        <tr><td>10002</td><td>张三</td><td>高数</td><td>94</td></tr>
        <tr><td>10001</td><td>赵二</td><td>线数</td><td>77</td></tr>
        <tr><td>10002</td><td>张三</td><td>线数</td><td>61</td></tr>
     </table>
     </span>
     <input type="submit" name="Excel" value="导出表格" onclick="test()"/>
     <input type="hidden" id="tableInfo" name="tableInfo" value=""/>
 </form>
 </body>
 </html>

upload_json.jsp

 <%@ page language="java" contentType="text/html; charset=UTF-8"
     pageEncoding="UTF-8"%>
 <%@ page import="java.util.*,java.io.*"%>
 <%@ page import="java.text.SimpleDateFormat"%>
 <%@ page import="org.apache.commons.fileupload.*"%>
 <%@ page import="org.apache.commons.fileupload.disk.*"%>
 <%@ page import="org.apache.commons.fileupload.servlet.*"%>
 <%@ page import="com.opensymphony.xwork2.ActionContext"%>
 <%@ page
     import="org.apache.struts2.dispatcher.multipart.MultiPartRequestWrapper"%>
 <%@ page import="org.json.simple.*"%>
 <%
     //文件保存目录路径
     String savePath = pageContext.getServletContext().getRealPath("/")
             + "kindeditor/attached/";

     //文件保存目录URL
     String saveUrl = request.getContextPath() + "/kindeditor/attached/";

     //定义允许上传的文件扩展名
     HashMap<String, String> extMap = new HashMap<String, String>();
     extMap.put("image", "gif,jpg,jpeg,png,bmp");
     extMap.put("flash", "swf,flv");
     extMap.put("media",
             "swf,flv,mp3,wav,wma,wmv,mid,avi,mpg,asf,rm,rmvb");
     extMap.put("file",
             "doc,docx,xls,xlsx,ppt,htm,html,txt,zip,rar,gz,bz2");

     //最大文件大小
     long maxSize = 1000000;

     response.setContentType("text/html; charset=UTF-8");

     if (!ServletFileUpload.isMultipartContent(request)) {
         out.println(getError("请选择文件。"));
         return;
     }
     //检查目录
     File uploadDir = new File(savePath);
     if (!uploadDir.isDirectory()) {
         out.println(getError("上传目录不存在。"));
         return;
     }
     //检查目录写权限
     if (!uploadDir.canWrite()) {
         out.println(getError("上传目录没有写权限。"));
         return;
     }

     String dirName = request.getParameter("dir");
     if (dirName == null) {
         dirName = "image";
     }
     if (!extMap.containsKey(dirName)) {
         out.println(getError("目录名不正确。"));
         return;
     }
     //创建文件夹
     savePath += dirName + "/";
     saveUrl += dirName + "/";
     File saveDirFile = new File(savePath);
     if (!saveDirFile.exists()) {
         saveDirFile.mkdirs();
     }
     SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
     String ymd = sdf.format(new Date());
     savePath += ymd + "/";
     saveUrl += ymd + "/";
     File dirFile = new File(savePath);
     if (!dirFile.exists()) {
         dirFile.mkdirs();
     }
     MultiPartRequestWrapper wrapper = (MultiPartRequestWrapper) request;

     //获得上传的文件名
     String fileName = wrapper.getFileNames("imgFile")[0];//imgFile,imgFile,imgFile     

     //获得文件过滤器
     File file = wrapper.getFiles("imgFile")[0];

     //检查扩展名
     String fileExt = fileName.substring(fileName.lastIndexOf(".") + 1)
             .toLowerCase();
     if (!Arrays.<String> asList(extMap.get(dirName).split(","))
             .contains(fileExt)) {
         out.println(getError("上传文件扩展名是不允许的扩展名。\n只允许"
                 + extMap.get(dirName) + "格式。"));
         return;
     }

     //检查文件大小
     if (file.length() > maxSize) {
         out.println(getError("上传文件大小超过限制。"));
         return;
     }

     //重构上传图片的名称
     SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");
     String newImgName = df.format(new Date()) + "_"
             + new Random().nextInt(1000) + "." + fileExt;
     byte[] buffer = new byte[1024];

     //获取文件输出流
     FileOutputStream fos = new FileOutputStream(savePath + "/"
             + newImgName);

     //System.out.println("########" + saveUrl + "@@"+ newImgName);
     //获取内存中当前文件输入流
     InputStream in = new FileInputStream(file);
     try {
         int num = 0;
         while ((num = in.read(buffer)) > 0) {
             fos.write(buffer, 0, num);
         }
     } catch (Exception e) {
         e.printStackTrace(System.err);
     } finally {
         in.close();
         fos.close();
     }

     JSONObject obj = new JSONObject();
     obj.put("error", 0);
     obj.put("url", saveUrl + newImgName);
     out.println(obj.toJSONString());
 %>
 <%!private String getError(String message) {
         JSONObject obj = new JSONObject();
         obj.put("error", 1);
         obj.put("message", message);
         return obj.toJSONString();
     }%>

struts下载文件配置

 public String download() throws Exception {
       uploadFileName="中文.jpg";
         downStream = ServletActionContext.getServletContext()
                 .getResourceAsStream(inputPath);
         return SUCCESS;
     }

 <action name="download" class="upload.DownloadAction" method="download">
             <!-- 指定被下载资源的位置 -->
             <param name="inputPath">\download\中文.jpg</param>
             <!-- 配置结果类型为stream的结果 -->
             <result name="success" type="stream">
                 <!-- 指定返回下载文件的InputStream -->
                 <param name="inputName">downStream</param>
                 <!-- 指定下载文件的文件类型 -->
                 <param name="contentType">image/jpg</param>
                 <param name="contentDisposition">attachment;filename=${uploadFileName}</param>
                 <!-- 指定下载文件的缓冲大小 -->
                 <param name="bufferSize">4096</param>
             </result>
             <result name="input">/upload.jsp
         </result>
         </action>

 页面
     <a href="download.action">下载包含中文文件名的文件</a>
 /这一段代码我也是不知道是哪里的   先放上去  以后再看吧

 public String executeCommandUDownload(ActionContext context)throws Exception{
         HttpServletResponse response = context.getResponse();
         response.setCharacterEncoding("UTF-8");
         boolean isOnLine = false;
         String fileName = context.getRequest().getParameter("fileName");

                 Connection con = null;
         HttpServletRequest request = context.getRequest();
         String filePath = null;
         BufferedInputStream buffer=null;
         OutputStream out=null;
         try
         {
             con = this.getConnection(context);
             if("".equals(fileName) || fileName == null){
                 FileInfoBean bean = new FileInfoBean();
                 fileName = bean.findName(con, id);

             }

             File f = new File(filePath);
                       //检查该文件是否存在
             if(!f.exists()){
                 response.sendError(404,"File not found!");
                 return "File not found!";
             }
             buffer = new BufferedInputStream(new FileInputStream(f));
             byte[] buf = new byte[1024];
             int len = 0;

             response.reset(); //非常重要
             if(isOnLine){ //在线打开方式
                 URL u = new URL("file:///"+filePath);
                 response.setContentType(u.openConnection().getContentType());
                 response.setHeader("Content-Disposition", "inline; filename="+(f.getName()).getBytes("gbk"));
             //文件名应该编码成UTF-8
             }
             else{ //纯下载方式

                 response.setContentType("application/x-msdownload"); 

                 response.setHeader("Content-Disposition", "attachment; filename=" + java.net.URLEncoder.encode(f.getName(),"UTF-8")); 

             }
             out = response.getOutputStream();
             while((len = buffer.read(buf)) >0)
                 out.write(buf,0,len);
         }catch(Throwable e)
         {
             e.printStackTrace();
         }finally
         {
             try
             {
                 buffer.close();
                 out.close();
             }catch(Throwable e)
             {
                 e.printStackTrace();
             }
         }
         return "";
     }

最新文章

  1. Windows 批处理设置dns ,解决能上qq不能开网页
  2. 如何让 height:100%; 起作用
  3. Web前端开发基础 第四课(盒代码模型)
  4. php pod
  5. 怎样用JS来添加CSS样式
  6. javascript数据变量类型判断(JS变量是否是数组,是否是函数的判断)
  7. 队列(链式存储)C++模板实现
  8. PHPCMS修改域名
  9. 通过EntityFramework来操作MySQL数据库
  10. 4、公司经营的业务来源 - CEO之公司管理经验谈
  11. PyCharm安装Pygame方法
  12. 面试官:说说一条查询sql的执行流程和底层原理?
  13. 用Maven快速生成带有依赖的可执行jar包
  14. python操作samba
  15. JSP 前端的一些应用
  16. ORM常用字段和参数
  17. Mobile first! Wijmo 5 + Ionic Framework之:费用跟踪 App
  18. 控件_SeekBar与RatingBar
  19. charAt和String的用法
  20. 利用Python的collections包下Counter的类统计每个数据出现的个数

热门文章

  1. jQuery中的选择器(上)
  2. GUI Design Studio——如何创建项目展示文件
  3. hadoop2.7.2单机与伪分布式安装
  4. MyBatis通用Mapper开发
  5. MySQL 开启慢查询日志
  6. GPU编程-Thread Hierarchy(3)
  7. RPM安装软件
  8. SDWebImage源码阅读-第三篇
  9. sleep()
  10. 关于Oracle、SqlServer 的sql递归查询