简体   繁体   中英

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?

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);
                });
            });   
        });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM