appengine send data as a file download

2020-07-26 15:01发布

I'm new to python and appengine.So I have this simple problem.I want to send the server data and have the server send it back as a file download.I can get a file to download if I do it before a page loads. But after that I can't get the download.Here is what I have right now:

class UploadHandler(webapp.RequestHandler):

  def get(self):
    try:    
        xml=parseString(self.request.body)
        result=sanitize(xml)
        if result == None:
          text=xml.toxml('UTF-8')
          name="file.xml"   
          self.response.out.write(text)
          self.response.headers.add_header('Method','get')
          self.response.headers.add_header('Content-Type','text/xml')
          self.response.headers.add_header('name',name)
          self.response.headers.add_header('Content-Disposition','attachment')
          self.response.headers.add_header('filename',name)
          self.response.headers.add_header('Content',text)
   except:
        print self.request.body

And here is the javascript to call it:

        var text=getMarkup();
        new Ajax.Request("http://localhost:8080/file",{
        method:'get',
        contentType:"text",
        postBody:text,
        onSuccess:function(){
            console.log(transport.responseText);            
        },          
        onFailure: function(){ 
            console.log('Could not load file...'); 
        },
        onException: function(req,exception) {
            console.log(exception);
            return true;
            }, 
        });

I've tried changing both pieces many different ways.I can get a response, but I can't get it to go to the downloads.If I use the same code for the main page it works though.What am I missing?

Finally got it.... I use the example on this page here only I sent the url back as the response and used window.open in the "onsuccess" handler to open it.

The problem with the blobstore is that the files are saved on the server and other people can view them, so my best solution is just to use a global variable to save the data from the post and then pass it to get and call get from javascript with window.open().

2条回答
甜甜的少女心
2楼-- · 2020-07-26 15:26

I think this will help

import mimetypes
...... 

(content_type, _) = mimetypes.guess_type(name)
self.response.headers['Content-Type'] = content_type
self.response.headers['Content-Disposition'] = 'attachment; filename=' + name
self.response.out.write(text) 

By the way. You can also use the blobstore to save your file and download the blob file.

查看更多
迷人小祖宗
3楼-- · 2020-07-26 15:47

Have you tried Content-Type: application/force-download? It will indicate that you are sending a file from server and that user would like to download (not view) it.

self.response.headers.add_header('Content-Type','application/force-download')
查看更多
登录 后发表回答