java实现下载在线文件

来源:互联网 发布:c语言 幂函数 编辑:程序博客网 时间:2024/04/29 05:14

现在做的是,我知道一个文件的url 链接,需要点击后下载

1.java代码

package com.test;import java.io.ByteArrayOutputStream;import java.io.IOException;import java.io.InputStream;import java.io.OutputStream;import javax.servlet.http.HttpServletResponse;import org.apache.commons.lang3.StringUtils;import org.apache.http.HttpResponse;import org.apache.http.HttpStatus;import org.apache.http.client.HttpClient;import org.apache.http.client.methods.HttpGet;import org.apache.http.impl.client.DefaultHttpClient;public class DownFile {    public static byte[] downLoad(String imgURL){        // 构造HttpClient的实例        HttpClient httpClient = new DefaultHttpClient();        if(StringUtils.isBlank(imgURL)){            return null;        }        HttpGet httpPost = new HttpGet(imgURL);       try {                HttpResponse response = httpClient.execute(httpPost);                 if (HttpStatus.SC_OK == response.getStatusLine().getStatusCode()) {                     InputStream in =response.getEntity().getContent();                     ByteArrayOutputStream outStream = new ByteArrayOutputStream();                          byte[] data = new byte[1024];                          int count = -1;                          while((count = in.read(data,0,1024)) != -1)                              outStream.write(data, 0, count);                          data = null;                          return outStream.toByteArray();                   }            } catch (IllegalStateException e) {                e.printStackTrace();            } catch (IOException e) {                e.printStackTrace();            }        return null;    }    /**     * 文件下载     * @param filePath 文件路径     * @param response      * @throws Exception     */    public void downLoad(String filePath, HttpServletResponse response,String fileName) throws Exception {      byte[] buf = this.downLoad(filePath);      response.reset(); // 非常重要      response.setContentType("application/x-msdownload");      response.setHeader("Content-Disposition", "attachment; filename=" + fileName);      OutputStream out = response.getOutputStream();      out.write(buf);      out.close();  }}

2.jsp页面

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%><%@ page import="com.test.*"%><%String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + request.getContextPath();response.setContentType("application/x-msdownload");String file_url = request.getParameter("file_url");new DownFile().downLoad("http://7xrftx.com1.z0.glb.clouddn.com/03.png", response,"1.png");out.clear();out = pageContext.pushBody();%>
原创粉丝点击