Search code examples
javascriptfilesavepromptdata-uri

Using data URIs to prompt the user to save files


I'm writing a web application which allows a user to select a PNG file, write an iTXt chunk to it and then save it back to their local file system. I would use the new FileWriter API to do so but currently only Google Chrome has added support for it.

Since my file is represented in memory as a binary string I use data URIs to prompt the user to save the file as follows:

window.location.href = "data:application/octet-stream;base64," + btoa(blob);

Since the mime-type is application/octet-stream the browser prompts the user to open or save it. However the problem is that the user does not know which type of file it is. So the user has to add the file extension manually.

Currently I alert the user which extension the file needs to be saved with. However this seems like an inelegant solution. Is there a better way to achieve the same result?


Solution

  • If this were HTTP, then you'd either have to set the content disposition to attachment, to get the file saved even if its mime type is known, or to set the file name for an attachment of octet-stream type. Neither of these headers can be emulated using the data: URI, though, so I see no way to open a “Save as…” dialog using such a URI.

    Others have asked how to open a save file dialog for a js variable, and judging from the answers there, there appears to be ready-to-use solutions which work as long as the client has Flash installed (and not blocked).

    So perhaps you might try severl solutions, starting with the FileWriter you mention, trying a flash-based approach if that isn't available, and falling back to data: URI with an alert message about the file name extension. That way you could probably achieve the best result possible for each client.