java实现下载在线文件

现在做的是,我知道一个文件的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();
%>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值