How to share file object from sketchup to javascript


This is a late reply to “How to share file object from sketchup to javascript?”. Here’s how to load the content of a file from JavaScript code, running embedded in SketchUp (2017-2020), in an HtmlDialog. We can “simply” make an XMLHttpRequest object and point it to the local full path of the file. I expected the JavaScript code to deny such a request, but it doesn’t. I guess it’s either because it’s running embedded, or because I’m using htmldialog.set_file, which gives the dialog box a URL that is from a local file as well (I didn’t try with htmldialog.set_html or set_url).

The html contains:

   <script type="text/javascript">
	function send_file(absolute_file_path) {
	    var req = new XMLHttpRequest();
	    req.onload = function () {
	        var blob = req.response;   // or req.responseText if you want plain text
	        if (blob == null) {
	            // oops, file couldn't be read
	        else {
	            // blob contains the file content.
	            // example usage: send it out with POST
	            var formdata = new FormData();
	            formdata.set("description", "...");
	            formdata.set("file", blob);

	            var upreq = new XMLHttpRequest();
	            upreq.onload = function () {
	                // should check for success or failure
	  "POST", "");
	    req.responseType = "blob";   // could be "text" if you expect a text file"GET", absolute_file_path);

This will be useful for my use case because I want to send the file’s content as part of a WebSocket connection, which is not supported by Ruby. Also, I’m trusting the browser’s support for “https” to stay very up-to-date, unlike the one included with an old version of Ruby linked with an old version of OpenSSL.

Hope it is useful to someone else.