Java实现文件下载

package com.controller;

import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.util.IOUtils;
import com.ptac.b2b.adapter.car.business.car.vo.HwDownloadFileVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.HttpVersion;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.*;

@Api(tags = {"文件下载"})
@RestController
@RequestMapping(value = "/file")
public class FileDownloadController {

    @PostMapping("/downloadFile")
    @ApiOperation(value = "下载文件", notes = "下载文件", httpMethod = "POST")
    public void downloadFile(HttpServletResponse response,@org.springframework.web.bind.annotation.RequestBody HwDownloadFileVo hwDownloadFileVo) {
        String url ="https://www.baidu.com?aa=1";
        // 创建默认的httpClient实例.
        CloseableHttpClient httpclient = HttpClients.createDefault();
        // 创建httpPost
        HttpPost httpPost = new HttpPost(url);
        httpPost.setProtocolVersion(HttpVersion.HTTP_1_0);
        try {
            // 设置请求头参数
            httpPost.setHeader("ID", "============");
            httpPost.setHeader("APPKEY", "=======");
            JSONObject paramMap = new JSONObject();
            paramMap.put("docId", hwDownloadFileVo.getDocId());
            HttpEntity entitys = new StringEntity(paramMap.toJSONString(), ContentType.create("application/json", "utf-8"));
            httpPost.setEntity(entitys);
            CloseableHttpResponse httpResponse = httpclient.execute(httpPost);
            // 获取第三方接口放在Response中的文件名
            Header[] headers = httpResponse.getHeaders("content-disposition");
            if (headers != null && headers.length > 0) {
                String contentDispositionValue = headers[0].getValue();
                // 设置文件名,这里没用加密文件名,可以自己设置
                response.addHeader("Content-Disposition", contentDispositionValue);
            }
            response.setContentType("application/octet-stream;charset=utf-8");
            HttpEntity entity = httpResponse.getEntity();

            InputStream inputStream1 = entity.getContent(); //获取输入流
            //  保存流 从这里到重置游标
            //  附件第一次下载没问题再下载有时候就报错,然后参照其他博主的方法,将流先保存下来
            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            BufferedInputStream br = new BufferedInputStream(inputStream1);
            byte[] b = new byte[1024];
            for (int c = 0; (c = br.read(b)) != -1;)
            {
                bos.write(b, 0, c);
            }

            br.close();
            ByteArrayInputStream inputStream = new ByteArrayInputStream(bos.toByteArray());
            // 第一次读流
            StringBuffer out = new StringBuffer();
            byte[] b1 = new byte[1024];
            for (int n; (n = inputStream.read(b1)) != -1;) {
                out.append(new String(b1, 0, n));  //这个可以用来读取文件内容 并且文件内容有中文读取出来也不会乱码
            }
            // 判断文件是否存在
            String resultHtml = out.toString();
            int firstIndex = resultHtml.indexOf("\n");
            if(firstIndex < 0){

            }
            // 重置游标
            inputStream.reset();
            // 输出文件
            ServletOutputStream outputStream = response.getOutputStream();
            try {
                byte[] oBuff = new byte[1024];
                int iSize;
                while (-1 != (iSize = inputStream.read(oBuff))) {
                    outputStream.write(oBuff, 0, iSize);
                }
                outputStream.flush();
            } finally {
                IOUtils.close(outputStream);
                IOUtils.close(inputStream);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                httpclient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值