0

I am using Google App Engine (python) and have a data: url of a PNG image available on the server. The PNG image was never in a file, as it was generated from some canvas code using toDataUrl() and ajaxed to the server. I would like to allow the user to click a button and be able to select a filename and save the PNG image locally. The Save As dialog box would supply a default filename.png. The target browser is FireFox. I have supplied sample code that doesn't work. There are several questions on stackoverflow that are somewhat like this one, but each is a little different.

I am setting content-disposition as attachment with a suggested filename. I set the header content-type to application/octet-stream. But I don't get the SaveAs dialog. What am I missing?

The app.yaml file is the standard

application: saveas
version: 1
runtime: python
api_version: 1

handlers:
- url: /.*
  script: main.py

The index.html is as follows:

<!DOCTYPE html>
<html lang="en">

<head>
<meta charset="utf-8"/>

<script>

function saveAsPng()
{
var alldata;
var httpRequest;
var response;
var myheaders;

httprequest = new XMLHttpRequest();

if ( !httprequest )
   {
   alert("In saveAsPng, XMLHttpRequest failed.");
   return;
   }

/* Make this a json string */
alldata = JSON.stringify("no data");

try
   {
   httprequest.open('POST', '/handlebitmap', true);
   httprequest.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
   httprequest.setRequestHeader("Content-length", alldata.length);
   httprequest.setRequestHeader("Connection", "close");
   httprequest.onreadystatechange = function() 
      {
      if ( httprequest.readyState == 4 )
         {
         if (httprequest.status == 200) 
            {
            /* a status of 200 is good. */
            response = null;
            try 
               {
               response = JSON.parse(httprequest.responseText); 
               } 
            catch (e) 
               {
               response = httprequest.responseText;
               }

            if ( response == "error" )
               {
               alert("In saveAsPng callback, response == error");
               return false;
               }
            else
               {
               /* This is the successful exit. */

               //alert("response = " +response);

               window.location.href = response;   

               return true;
               }
            }
         else
            {
            /* httprequest.status was not 200, so must be an error. */
            alert("saveAsPNG callback, status = " +httprequest.status);
            return false;
            }

         }   /* End of if where readyState was 4. */

      }   /* End of the callback function */

   /* Make the actual request */
   httprequest.send(alldata);
   }
catch(e)
   {
   alert("In saveAsPng, Can't connect to the server");
   }

}   /* End of the saveAsPng function */

The python code is as follows:

# !/usr/bin/env python

import os
import base64

from google.appengine.ext import webapp
from google.appengine.ext.webapp import template
from google.appengine.ext.webapp import util

class MainPage(webapp.RequestHandler):
    """ Renders the main template."""
    def get(self):
        template_values = { 'title':'Test Save As PNG', }
        path = os.path.join(os.path.dirname(__file__), "index.html")
        self.response.out.write(template.render(path, template_values))

class BitmapHandler(webapp.RequestHandler):
    """ Shows the Save As with a default filename. """
    def post(self):
        origdata = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAYAAACNbyblAAAAHElEQVQI12P4//8/w38GIAXDIBKE0DHxgljNBAAO9TXL0Y4OHwAAAABJRU5ErkJggg=="
        urldata = "iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAYAAACNbyblAAAAHElEQVQI12P4//8/w38GIAXDIBKE0DHxgljNBAAO9TXL0Y4OHwAAAABJRU5ErkJggg=="
        decodeddata = base64.b64decode(urldata) 
        self.response.headers['Content-Type'] = 'application/octet-stream'
        self.response.headers['Content-Disposition'] = 'attachment; filename="untitled.png"'
        self.response.out.write(decodeddata)

def main():
    app = webapp.WSGIApplication([
        ('/', MainPage),
        ('/handlebitmap',BitmapHandler),
        ], debug=True)
    util.run_wsgi_app(app)

if __name__ == '__main__':
    main()

{{title}}

RFF
  • 271
  • 1
  • 2
  • 10

1 Answers1

0

Perhaps you want to change the "def post" to a "def get"? I just tried your sample and it seemed to be working as expected after that change (only tried /handlebitmap)

Bemmu
  • 17,849
  • 16
  • 76
  • 93
  • I tried GET instead of POST, but the final result is always: localhost:8080/%ED%BF%BDPNG HTTP/1.0 404 Not Found. I am not sending any data to the server, just getting a data: url back. I must be doing something fundamentally wrong. – RFF Apr 24 '12 at 14:53