JQuery通过Post发送Json到后台将请求的octet-stream转为文件下载

问题描述

  • 服务器在不想直接抛出一个真实文件url给时,浏览器端从服务器请求回的octet-stream文件流在调试工具下可见乱码式Response,却无法弹出下载框下载文件。

1. 搭建服务

先用python Flask框架搭建一个简单的后台用于做数据接口。Flask非常的方便,我也是第一次用,感觉和webpy挺像的,比Django简单。首先建一个 DemoDownload/ 文件夹,在此文件夹里再建一个 Server.py 文件和一个 templates/ 文件夹,templates/ 内建一个 ·download.html 文件。文件层次结构入。

- DemoDownload/
	- Server.py
	- templates/
		- download.html

2. 服务接口

Server.py 添加代码如,其中 d://test.txt 文件为任意一个测试文件,并将它放在服务访问不到的地方。

#!/usr/bin/python
# coding:utf-8
import json
from flask import Flask
from flask import request
from flask import make_response
from flask import render_template 
import io
app = Flask(__name__)

@app.route('/downloadTxt' , methods=[ 'POST'])
def download():
    # 接收表单
    a = request.get_data().decode('utf-8')
    print(a)
    b = request.form
    print(b)
    data = b.to_dict()
    print(data)
    file = open("d://test.txt", 'rb')
    response = make_response(file.read())
    file.close()
    response.headers['content-type'] = 'application/octet-stream;charset=utf-8'
    response.headers['content-disposition'] = 'attachment;filename=' + 'test.txt'
    return response

@app.route('/download', methods=["GET"])
def downloadDocx():
    html = render_template('download.html')
    return html

if __name__ == '__main__':
    app.run(host='0.0.0.0', port=8765, debug=True)

3. 前端代码

download.html 如下。

<html>
<head>
    <script src="https://cdn.staticfile.org/jquery/1.10.2/jquery.min.js"></script>
    <script>
        var DownLoadFile = function (options) {
        var config = $.extend(true, {
            method: 'post'
        }, options);
        var $iframe = $('<iframe id="down-file-iframe" />');
        var $form = $('<form target="down-file-iframe" method="' + config.method + '" />');
        $form.attr('action', config.url);
        for (var key in config.data) {
            $form.append('<input type="hidden" name="' + key + '" value="' + config.data[key] + '" />');
        }
        $iframe.append($form);
        $(document.body).append($iframe);
        $form[0].submit();
        $iframe.remove();
        };
        var params = {
	        id: 6,
            name: "dog",
            age: 12
        };
        function pst() {
            DownLoadFile({
                url: "http://localhost:8765/downloadTxt", //请求的url
                data: params,
            });
        }
    </script>    
</head>
<body>
    <button onclick="pst()">Download</button>
</body>
</html>

4. 测试

启动服务的命令为,注意要有Python环境并安装了Flask框架,另外缺啥包就 pip install [ThisPackage] 懂我意思吧。

python Server.py

浏览器访问 http://localhost:8765/download ,点下载按钮直接跳出下载文件即完成。
.

.
.
.
.
.
.


桃花仙人种桃树,又摘桃花换酒钱_

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值