Fantaxico
Fantaxico

Reputation: 98

Google Extension - Send a local file via POST request in Javascript?

I want to develop a Google Chrome extension that downloads a PDF from a server and then uploads it directly to another page. Downloading the document was easy. However uploading seems harder to do. I need to access my local file explorer, cache the file in the code and then send it via POST request. Is there any way to accomplish that ?

Upvotes: 0

Views: 154

Answers (1)

Fantaxico
Fantaxico

Reputation: 98

I found a solution with HTML5 Filesystem. The received File Object is a type of Blob which can be send via XMLHttpRequest. Although it didn't work for some reason, I appended it to a FormData that I knew worked. The downside is that it only works in the root directory of the extension.

    chrome.runtime.getPackageDirectoryEntry(function (root) {
            root.getFile("myFile.pdf", {}, function (fileEntry) {
                fileEntry.file(function (file) {
                    var formData = new FormData();
                    formData.append("file", file);
                    var http = new XMLHttpRequest();
                    var url = 'myUrl';
                    http.open('POST', url, true);  
                    http.onreadystatechange = function () {
                        if (http.readyState == 4 && http.status == 200) {
                            alert(http.responseText);
                        }
                    }
                    http.send(formData);
                });
            });   
        });

Upvotes: 1

Related Questions