java 通过url下载文件到浏览器

我就是我 2023-02-22 15:53 107阅读 0赞

前端传来url地址与文件名,下载文件到浏览器

  • 代码 (这里模拟,直接在代码里写了url,可以拼接在url后进行截取)
  • 请求接口

    1. @GetMapping("/findOperatorBarVO2")
    2. @ApiOperation(value = "下载")
    3. public void findOperatorCharBar2(HttpServletResponse response)throws IOException{
    4. toDownload(response);
    5. }
  • 下载方法

    1. public static void toDownload( HttpServletResponse response) {
    2. ServletOutputStream out = null;
    3. InputStream inputStream = null;
    4. try {
    5. //路径
    6. String path = "http://10.202.61.66:11111/KEDFSFile/M00/00/1E/Cso9Ql7Z61CAZtQcAAAGqKgzHds335.txt";
    7. // 取得文件的后缀名。
    8. String ext = path.substring(path.lastIndexOf(".") + 1).toLowerCase();
    9. //文件名
    10. String pdfName = "问题."+ext;
    11. // 获取外部文件流
    12. URL url = new URL(path);
    13. HttpURLConnection conn = (HttpURLConnection) url.openConnection();
    14. conn.setConnectTimeout(3 * 1000);
    15. //防止屏蔽程序抓取而返回403错误
    16. conn.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");
    17. inputStream = conn.getInputStream();
    18. /** * 输出文件到浏览器 */
    19. int len = 0;
    20. // 输出 下载的响应头,如果下载的文件是中文名,文件名需要经过url编码
    21. response.setContentType("application/x-download");
    22. response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(pdfName, "UTF-8"));
    23. response.setHeader("Cache-Control", "no-cache");
    24. out = response.getOutputStream();
    25. byte[] buffer = new byte[1024];
    26. while ((len = inputStream.read(buffer)) > 0) {
    27. out.write(buffer, 0, len);
    28. }
    29. out.flush();
    30. } catch (Exception e) {
    31. e.printStackTrace();
    32. } finally {
    33. if (inputStream != null) {
    34. try {
    35. inputStream.close();
    36. } catch (Exception e) {
    37. }
    38. }
    39. if (out != null) {
    40. try {
    41. out.close();
    42. } catch (Exception e) {
    43. }
    44. }
    45. }
    46. }
  • 前端代码

    1. window.location.href = "http://localhost:9090/xx/evaOperator/findOperatorBarVO2";

发表评论

表情:
评论列表 (有 0 条评论,107人围观)

还没有评论,来说两句吧...

相关阅读