简体   繁体   中英

Send files via XMLHttpRequest on another Server

i like try to send a POST form with attached files via javascript XMLHttpRequest.

Here is my Code:

window.addEventListener('load', function() {
    var button = document.getElementById('start_file_upload_button');
    button.addEventListener('click', function()
        {
        document.getElementById("file_upload_button_button").style.display = "none";
        var mfs         = document.getElementsByName('MAX_FILE_SIZE')[0].value,
            to_up_files = document.getElementById('to_upload_files_field'),
            status      = document.getElementById('file_upload_status_text'),
            errorlog    = document.getElementById('file_upload_error_log'),
            progress    = document.getElementById('file_upload_progress_bar');
        for(var i = 0; i < document.getElementById('to_upload_files_field').files.length; ++i) {
            document.getElementById('remove_link_' + i).style.display = "none"; }
        for(var i = 0; i < <?php echo $__CONFIG['UPLOAD']['MAX_FILE_AT_ONCE']; ?>; ++i)
            {
            if(typeof(document.getElementById('to_upload_files_field').files[i]) == "undefined") break;
            var upload   = document.getElementById('to_upload_files_field').files[i],
                filename = upload.name,
                filesize = upload.size,
                mfs      = mfs; alert(filename);
            if(filesize > <?php echo $USER_DATA['UPLOAD_MAX_FILE_SIZE']; ?>)
                {
                var errorelem  = document.createElement('span');
                var errorbreak = document.createElement('br');
                errorelem.appendChild(document.createTextNode('Die Datei "' + filename + '" ist zu Groß'));
                errorelem.appendChild(errorbreak);
                errorlog.appendChild(errorelem);
                break;
                }
            if(<?php echo $USER_DATA['SPACE_MAX']; ?> < (filesize + <?php echo $USER_DATA['SPACE_USED']; ?>))
                {
                var errorelem  = document.createElement('span');
                var errorbreak = document.createElement('br');
                errorelem.appendChild(document.createTextNode('Die Datei "' + filename + '" past nicht mehr auf die Platte'));
                errorelem.appendChild(errorbreak);
                errorlog.appendChild(errorelem);
                break;
                }
            if(filesize > (<?php echo $USER_DATA['TRAFFIC_PER_DAY'] - $USER_DATA['TRAFFIC_USED']; ?>) && (<?php echo $USER_DATA['TRAFFIC_PER_DAY'] - $USER_DATA['TRAFFIC_USED']; ?>) != 0)
                { // SPERRE EINBAUEN DAS ES NUR GEPRÜFT WIRD WENN DIE TRAFFIC ÜBERWACHUNG AKTIVIERT IST
                var errorelem  = document.createElement('span');
                var errorbreak = document.createElement('br');
                errorelem.appendChild(document.createTextNode('Die Datei "' + filename + '" braucht mehr traffic als du hast'));
                errorelem.appendChild(errorbreak);
                errorlog.appendChild(errorelem);
                break;
                }
            status.innerHTML = "Lade " + filename + " hoch...";
            var request = new XMLHttpRequest();
            request.open('POST', 'http://www.domain.tld/user/upload/', true);
            request.setRequestHeader('Content-Type', 'multipart/form-data');
            request.upload.addEventListener('progress', function(evt)
                {
                var uploaded = Number((100 / evt.total) * evt.loaded).toFixed(2);
                progress.innerHTML = "Upload zu " + uploaded + "% fertig";
                if(uploaded = 100.00)
                    {
                    progress.innerHTML = "Datei wird verarbeitet... Bitte warten...";
                    }
                }, false);
            request.addEventListener('load', function(evt) {
                alert("lol2"); }, false);
            var data = new FormData();
            data.append('upload_key', '<?php echo $upload_key; ?>');
            data.append('MAX_FILE_SIZE', mfs);
            data.append('file', upload);
            request.send(data);
            request.onload = function()
                {
                if(this.status == 200)
                    {
                    alert("lol");
                    }
                else
                    {
                    alert("Some Upload Error");
                    }
                };
            }
        }, false);
    }, false);

The Script works great and without problems when i'll send it to " http://www.domain.tld/user/upload/ " but i like to send it to " http://sub.somain.com/store/ " and this is not working, why?

Console log by send to "www.domain.tld":

[12:21:51.085] POST http://www.domain.tld/user/upload/ [HTTP/1.1 200 OK 5ms]

Console log by send to "sub.domain.tld":

[12:21:17.786] OPTIONS http://sub.domain.tld/store/ [HTTP/1.1 200 OK 7ms]

The servers run the same script, what can i do?

Javascript will not allow you to make requests between domains, howewer, this behavior can be changed if the server sends Access-Control-Allow-Origin header with the name of whitelisted domain.

CORS

As I've said, you can yse special response header to allow cross-domain request. This method is called CORS - Cross Origin resource sharing .
It is used like that:

header("Access-Control-Allow-Origin: www.domain.tld");

Unfortunatelly, this was only recently introduced and has poor browser support.

CORS Browser support

JSONP

Another method to fire cross domain request is JSONP. This can only be applyed to GET requests. Because you are sending POST, I will not introduce this further.

Iframe

You may have forgotten about possibility of using an Iframe. Of course, in that case you will not get any return values and it will be impossible to monitor upload process. But you can still inform user about sucess if you fire alert() function in the iframe. Also, you can reload page from the iframe:

window.top.location = "domain.com/script.php?upload=sucessfull";

You're breaking the "same origin policy". You can return the Access-Control-Allow-Origin header, which will tell the browser to allow the request, however browser support isn't 100% . Take a look at the documentation for your web server or programming language .

If you need 100% browser support then you might be better off uploading into /tmp on the parent domain, and then firing off a cURL request to the sub-domain.

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