文件服务器--文件下载

1. js代码

    注意:调用文件下载接口时,不要使用ajax。使用ajax会导致浏览器的下载功能无法正常触发。因此,我们使用JavaScript的表单模板进行接口调用和数据提交。

$(function () {
  $('#fileDownload').click(function () {
    //后台方法、文件类型、文件名
    downloadTemplate('/fileDownload', 'filename', 'test');
  });
});
function downloadTemplate(action, type, value){
  var form = document.createElement('form');
  document.body.appendChild(form);
  form.style.display = "none";
  form.action = action;
  form.id = 'pdf';
  form.method = 'post';
  //隐藏标签,可以存放想要传递的参数
  // var newElement = document.createElement("input");
  // newElement.setAttribute("type","hidden");
  // newElement.name = type;
  // newElement.value = value;
  // form.appendChild(newElement);

  form.submit();
}

2. java代码

@RestController
public class FileDownloadController {

  @PostMapping("fileDownload")
  public void fileDownload(HttpServletRequest request, HttpServletResponse response){

    String fileUrl = "static/pdf/SpringCloudDalston.pdf";
    String serverUrl = "http://localhost:9097";
//    String fileName= fileid.substring(fileid.lastIndexOf("/") + 1);
    String fileName = "123.pdf";
    String filePath = serverUrl + "/" + fileUrl;

    HttpURLConnection urlConn = null;
    BufferedInputStream bis = null;
    BufferedOutputStream bos = null;

    try {
      //调用文件服务器的地址,获取其输入流
      URL url = new URL(filePath);
      urlConn = (HttpURLConnection) url.openConnection();
      urlConn.connect();
      InputStream inputStream = urlConn.getInputStream();
      //将输入流中获取到的数据通过输出流输出
      if (inputStream != null) {
        bis = new BufferedInputStream(inputStream);
        bos = new BufferedOutputStream(response.getOutputStream());

        //设置响应头
        //attachment下载
        response.setHeader("Content-Disposition","attachment;filename=" + new String(fileName.getBytes(),"ISO8859-1"));
        //类型pdf
        response.setContentType("application/pdf");

        int readlen = 0;
        byte[] buffer = new byte[1024];
        while ((readlen = bis.read(buffer, 0, buffer.length)) != -1) {
          bos.write(buffer, 0, readlen);
        }
      }
    } catch (Exception e) {
      e.printStackTrace();
    } finally {
      try {
        if(null!=bos){
          bos.close();
        }
        if(null!=bis){
          bis.close();
        }
        urlConn.disconnect();
      } catch (IOException e) {
        e.printStackTrace();
      }
    }

  }

}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值