Question

Every so often (seems about once a year) I get a chance to play with JS.
While not proficient, I'm comfortable enough to get the job done if I have some good references.

At this point, I feel like I'm just not coming up with the right search terms to find anything useful.

GOAL:
I'm looking for examples, tips, advice and/or links to any documentation/articles/instructions that my help.

BACK STORY:
We have a vendor on whose site we search part numbers.
The results page has basic spec's and stat's, and there is a download link for a pricing sheet.
We have developed a tool to parse through the sheet and automatically enter the pricing into our system. The current workflow is to download the file and save it locally, and then upload the file to our form.

TASK:
What I intend to do is make a bookmarklet to cut out a few steps.
I'd like to have the JS initiate the DL and then POST the file right off to the current form-processing action url (straight from memory/temp location).

SUMMARY:
Of course, snippets and examples are always awesome!!
Beyond that, any-and-every bit of sharing will be appreciated

Was it helpful?

Solution

Assuming you're passing the same origin policy and that your browser supports XMLHttpRequest, Blob, FormData

function getThenUpload(fromURL, toURL) {
    var xhrFrom = new XMLHttpRequest();
    xhrFrom.onload = function () {
        var xhrTo = new XMLHttpRequest(),
            formData = new FormData();    // make file have <form> style
        formData.append('file', this.response); // set "name, value" of "<input>"
        xhrTo.open('POST', toURL);
        xhrTo.send(formData);             // upload file
    }
    xhrFrom.open('GET', fromURL);
    xhrFrom.responseType = 'blob';        // expecting file
    xhrFrom.send();                       // download file
}
getThenUpload('/file.txt', 'upload.php'); // start
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top