Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

using Javascript to upload a remote file on my server to a 3rd party server

I am using PHP to create an image file on my server. Now I need to upload this through a POST to a server of a 3rd party. Easiest would be to use a server side cURL script to accomplish that but I have to do it through my client, because it needs to be uploaded in the context of the active session between the client and the 3rd party server. The question is how can I achieve this easiest?

  1. Is it possible to use say an HTML form or AJAX call and upload the image from by giving it the URL? The thing is that the 3rd party back end does not accept URLs, it needs to be represented as if it was an upload through a web form...

  2. If that is not possible, I was thinking to use an AJAX call to download the image and save the contents to a variable. Then create a form that uploads the contents of the image as if a local file was selected in the form. How should I accomplish that?

When I upload a file through a web form and look at the HTTP headers being sent 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 like in this format and then submit that as data through an AJAX call? Where do I put the actual binary image data? I guess the Chrome developer tools suppress that data...

Thanks for any pointers.

like image 512
Joni Avatar asked Nov 14 '22 17:11

Joni


1 Answers

I think the easiest seems to be what you said, upload it to the 3rd party through your server. Is there a way for you to get whatever from the user's session through your PHP script?

Otherwise, you can try sending back to the client (perhaps via AJAX) the image in some encoded format, like base64, after your server has generate it, then build a custom XHR to send the file to the 3rd party... here's a sample:

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's 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);

See more info here (below the "The XMLHttpRequest object" section):
http://igstan.ro/posts/2009-01-11-ajax-file-upload-with-pure-javascript.html

like image 166
janechii Avatar answered Dec 14 '22 23:12

janechii