后端下载功能实现,在前端使用 ajax 接收

后端 下载功能实现

public void downloadFiles(HttpServletResponse response, String nowFileName, String rawFileName) {
   try {
        File file = new File(fileUrl + nowFileName);
        FileInputStream fileInputStream = new FileInputStream(file);
        InputStream fis = new BufferedInputStream(fileInputStream);
        byte[] buffer = new byte[fis.available()];
        fis.read(buffer);
        fis.close();
        response.reset();
        response.setCharacterEncoding("UTF-8");
        response.addHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(rawFileName, "UTF-8"));
        response.addHeader("Content-Length", "" + file.length());
        OutputStream outputStream = new BufferedOutputStream(response.getOutputStream());
        response.setContentType("application/force-download");
        outputStream.write(buffer);
        outputStream.flush();
        outputStream.close();
    } catch (FileNotFoundException e) {
        throw new RuntimeException(e);
    } catch (IOException e) {
        throw new RuntimeException(e);
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}
$(document).on("click",".auploadfilename",function(data){
            let filName = this.innerText;
            $.ajax({
                url: "./downloadFile",
                type: "post",
                data: {
                    nowFileName: attachments.get(filName),
                    rawFileName: filName,
                },
                dataType: 'binary',
                xhrFields: {responseType: 'blob'},
                success: function(result, status, xhr){
                    const fileName = filName;
                    // 可通过XMLHttpRequest对象,获取响应头
                    console.log(xhr);
                    // 浏览器兼容 参数Blob类型
                    const downloadURL = (window.URL || window.webkitURL).createObjectURL(result);
                    // 创建a标签
                    var a = document.createElement('a');
                    // 下载后文件的名字
                    a.download = fileName;
                    a.href = downloadURL;
                    document.body.appendChild(a);
                    a.click();
                    setTimeout(function () {
                        // 移除内存中的临时文件路径和为下载而创建的a标签
                        URL.revokeObjectURL(downloadURL);
                        a.remove();
                    }, 10000);
                }
            });
    })
好的,以下是一个简单的例子: HTML页面中,可以使用jQuery库的ajax方法发送请求并接收后端数据,示例代码如下: ```html <!DOCTYPE html> <html> <head> <title>AJAX Example</title> <script src="https://cdn.bootcss.com/jquery/3.5.1/jquery.min.js"></script> </head> <body> <div id="result"></div> <script> $.ajax({ url: "/api/data", // 后端接口地址 method: "GET", // 请求方法 success: function(data) { // 成功回调函数 $("#result").html(data); // 显示后端返回的数据 }, error: function() { // 失败回调函数 alert("请求数据失败!"); } }); </script> </body> </html> ``` 这里使用了jQuery库中的ajax方法,通过设置url、method、success和error参数来发送请求、处理响应和处理异常。其中,url表示后端接口地址,method表示请求方法(GET、POST、PUT等),success和error分别表示请求成功和失败时的回调函数。在success回调函数中,我们将后端返回的数据显示在页面上,这里使用了jQuery库的html方法。 后端接口可以根据具体需求来设计,这里以Python Flask框架为例,示例代码如下: ```python from flask import Flask app = Flask(__name__) @app.route('/api/data') def get_data(): data = "Hello, World!" return data if __name__ == '__main__': app.run() ``` 这里定义了一个路由/api/data,当接收到GET请求时,返回字符串"Hello, World!"。当然,实际应用中,我们可以从数据库中查询数据等,然后将结果返回前端页面。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值