Google App Engine getImageServingUrl with download

2019-09-13 23:36发布

I'm using getImageServingUrl method to generate URL to an image and it works nicely along with options listed at List of all the App Engine images service get_serving_url() URI options

I can add "d" option to force file download instead of just presenting it in the browser. The thing is that file name defaults to "unnamed.[ext]" (where [ext] is source file extension). Is there a way I can pass the original filename somewhere to the request?

I can use CloudStorageTools::serve to save file under given name but for example I can't use the image resizing features then.

1条回答
走好不送
2楼-- · 2019-09-14 00:17

I am not aware of any option that would allow this. But I have a concept for another way, that is a bit complicated, but might be a good option for you. You can use nginx to build a reverse proxy, that will serve the google images for you through your own domain. Then you could send the filename in your original request as a parameter. In nginx you can get rid of the filename parameter from the request before proxying the request and add it as a header to define the filename in the response. This is pretty straighforward as a process in your nginx config:

location /image-storage/ {
    expires 30d;

    #Get rid of headers to be overwritten
    proxy_hide_header Pragma;
    proxy_hide_header Cache-Control;
    proxy_hide_header Content-Disposition;

    #Add caching headers
    add_header Pragma public;
    add_header Cache-Control "public";
    #If the parameter "filename" is sent, use it as filename
    if ($arg_filename) {
        add_header Content-Disposition 'inline; filename="$arg_filename"';
    }
    #If the parameter "dl_filename" is sent, use it as filename and init download (attachment)
    if ($arg_dl_filename) {
        add_header Content-Disposition 'attachment; filename="$arg_dl_filename"';
    }

    #Proxy the request to google
    proxy_pass       https://lh3.googleusercontent.com/;
    proxy_set_header Host lh3.googleusercontent.com;

    proxy_set_header X-Real-IP $remote_addr;
    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;

    proxy_buffering off;
}

This way a url like: https://yourdomain.com/image-storage/longgoogletokenhere?dl_filename=test.jpg would be proxied to https://lh3.googleusercontent.com/longgoogletokenhere?dl_filename=test.jpg and the response would get new headers for caching and filename.

查看更多
登录 后发表回答