使用cherrypy下载文件

奥姆里

我有一台cherrypy服务器,用于从客户端生成REST API请求。

API中的一种方法不会返回JSON,而会返回CSV文件。

/myMethod/report/?name=a&fromRow=1&toRow=1000

我想通过单击按钮从客户端下载此文件。但是,必须通过小樱桃传递,而不是直接从客户端传递。

这是我的ajax函数:

  function myReport(name){
  $.ajax(  {
            url : '/myMethod/myReport?name='+name,
            type: 'POST',
            dataType: "text",
            success:function(data, textStatus, jqXHR) {
                window.open(data, "Statistics Report", "width=800, height=200", true);
            },
            error: function(jqXHR, textStatus, errorThrown)
            {
                alert('error')
            }
    });

  }

这是我的cherrypy函数:

@cherrypy.expose
def myReport(self, name):
    url = "myReport/?name=" + name + "&fromRow=1&toRow=1000"
    htmlText = self.general_url(url)
    cherrypy.response.headers['Content-Type'] = 'application/json'
    return htmlText

该值htmlText是文件的URL。我想将此值传递给window.open但是,已传递给的实际值window.open是CSV文件的内容,而不是该文件的URL链接(将打开一个新窗口,文件内容为URL)。我不想通过直接从ajax函数下载文件来“解决”问题,因为它必须通过cherrypy生成。

有人知道是什么问题吗?

诗人

当您查看的内容window.open,您会看到第一个参数是要在弹出窗口中打开的url,因此,如果您未在cherrypy端设置content-type响应标头,则弹出窗口自然会打开CSV内容。如果要显示文件的链接,则需要打开一个带有空url的弹出窗口,并将ajax结果提供给弹出窗口,例如在ajax调用的成功函数中;

var newWindow=window.open("", "Statistics Report", "width=800, height=200", true);
newWindow.document.body.innerHTML='<a href="'+data+'">'+data+'</a>';

如果要显示一个空的弹出窗口并开始下载,则;

newWindow.location.href=data;

但是,在小巧的方面,您需要像这样设置响应内容类型。

cherrypy.serving.response.headers["Content-Type"]='application/octet-stream';

否则,cherrypy将其设置为,text/html以便您的浏览器尝试在弹出窗口中显示它

本文收集自互联网,转载请注明来源。

如有侵权,请联系[email protected] 删除。

编辑于
0

我来说两句

0条评论
登录后参与评论

相关文章