Using Javascript to upload a remote file on my server to a third-party server

I am using PHP to create an image file on my server. Now I need to upload this via POST to a third party server. The easiest way would be to use the server side of the cURL script to execute this, but I have to do it through my client, because it needs to be loaded in the context of the active session between the client and the third-party server. The question is, how can I achieve this most easily?

  • Can I use an HTML form or an AJAX call and upload an image by specifying its URL? The fact is that a third-party third-party does not accept URLs, it should be presented as if it were a download via a web form ...

  • If this is not possible, I decided to use the AJAX call to load the image and save the contents in a variable. Then create a form that loads the contents of the image, as if the local file was selected on the form. How to do it?

When I upload a file via a web form and look at the sent HTTP headers, I see something like this:

------WebKitFormBoundary3ygta7rqeBm1krBO
Content-Disposition: form-data; name="MAX_FILE_SIZE"

10000000
------WebKitFormBoundary3ygta7rqeBm1krBO
Content-Disposition: form-data; name="uploadedfile"; filename="test.jpg"
Content-Type: image/jpeg


------WebKitFormBoundary3ygta7rqeBm1krBO--

Should I create a string similar to this format and pass it as data via an AJAX call? Where can I post the actual binary image data? I think Chrome Developer Tools suppress this data ...

Thanks for any pointers.

+5
source share
1 answer

, , , . PHP script?

( AJAX) , base64, , , XHR . :

var boundary = this.generateBoundary();
var xhr = new XMLHttpRequest;

xhr.open("POST", this.form.action, true);
xhr.onreadystatechange = function() {
    if (xhr.readyState === 4) {
        alert(xhr.responseText);
    }
};
var contentType = "multipart/form-data; boundary=" + boundary;
xhr.setRequestHeader("Content-Type", contentType);

for (var header in this.headers) {
    xhr.setRequestHeader(header, headers[header]);
}

// here our data variable that we talked about earlier
var data = this.buildMessage(this.elements, boundary);

// finally send the request as binary data
xhr.sendAsBinary(data);

. ( " XMLHttpRequest" ):
http://igstan.ro/posts/2009-01-11-ajax-file-upload-with-pure-javascript.html

+1

All Articles