java通用文件下载工具类

稍微修改就能使用


import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
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.InputStream;
import java.net.*;

/**
 * @ClassName URLUpload
 * @Deacription
 * @Author YJT
 * @Date 2020/9/25  14:22
 * @Effect:
 **/
@RestController
@RequestMapping(value = "/uploadPDF")
public class URLUpload {



    
    @RequestMapping("/upload")
    public void export(String fileName,String path,HttpServletResponse httpServletResponse) {
        final Logger logger = LoggerFactory.getLogger(URLUpload.class);
        ServletOutputStream out = null;
        InputStream inputStream = null;

        try {
            int indez = 0;
            if (path == null){
                logger.error("参数不正确,请检查参数!");
                return;
            }
            indez = path.lastIndexOf(".");
            String suffix = path.substring(indez);
            //文件名 让前端给
            logger.info("fileName = " + suffix);
            String pdfName;
            if (!fileName.trim().isEmpty()) {
                pdfName = fileName + suffix;
                logger.info("pdfName = " + pdfName);
            } else {
                pdfName = "公告" + suffix;

            }
            // 获取外部文件流
            logger.info("IS DOWNLOADING:invPdfUrl=" + path);
            URL url = new URL(null, path, new sun.net.www.protocol.https.Handler());
            String proxyAddress = "**********";  //代理服务器地址 ,有代理就添加,没有就删除
            int proxyPort = *****;  //代理端口号,有就添加,没有就删除
            Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(proxyAddress, proxyPort));
            HttpURLConnection conn = (HttpURLConnection) url.openConnection(proxy);  //创建连接
            conn.setConnectTimeout(30 * 1000);  //设置超时时间
            conn.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");  //防止屏蔽程序抓取而返回403错误
            inputStream = conn.getInputStream();


            //输出文件到浏览器
            // 输出 下载的响应头,如果下载的文件是中文名,文件名需要经过url编码
            httpServletResponse.setContentType("application/pdf");
            httpServletResponse.setContentType("application/msword");
            httpServletResponse.setContentType("application/powerpoint");
            httpServletResponse.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(pdfName, "UTF-8"));
            httpServletResponse.setHeader("Cache-Control", "no-cache");
            out = httpServletResponse.getOutputStream();  //获取输出流
            byte[] buffer = new byte[4096];  //生命字节数组
            int len = 0;
            while ((len = inputStream.read(buffer)) > 0) {  //每次读取1024字节的内容,判断内容是否大于0,如果大于0说明读取的有内容
                out.write(buffer, 0, len);  //把读取到的内容输出到本地硬盘
            }

            out.flush();  //刷新
            logger.info("DOWNLOAD SUCCESS!");
        } catch (IOException e) {

            logger.error("DOWNLOAD FAILED!", e);
            e.printStackTrace();
        } finally {
            if (inputStream != null) {
                try {
                    inputStream.close();
                } catch (IOException e) {
                	e.printStackTrace();
                }
            }
            if (out != null) {
                try {
                    out.close();
                } catch (IOException e) {
                	e.printStackTrace();
                }
            }
        }
    }
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值