Question

I would like to upload files to a remote server using the plupload library. Everything works with Chrome (32.0) and IE 10 using the html5 runtime but when I try with Firefox 27 (html5 runtime) or IE 8 (html4 runtime) I get an error Error #-200: HTTP Error..

Clientside script :

$(function() {
var uploader = new plupload.Uploader({
    browse_button: 'browse',
    url: 'https://remote.com/API/action.php',
    runtimes : 'html5,flash,silverlight,html4',
    flash_swf_url : './js/Moxie.swf',
    silverlight_xap_url : './js/Moxie.xap'
});

uploader.init();
uploader.settings.multipart_params = { 
       [...]
};

// PreInit events, bound before any internal events
uploader.bind('init', function(up, info) {
        console.log('[Init]', 'Info:', info, 'Features:', up.features);
        alert(info['runtime']);
});

uploader.bind('Error', function(up, err) {
    document.getElementById('console').innerHTML += "\nError #" + err.code + ": " + err.message;
});

document.getElementById('start-upload').onclick = function() {
    uploader.start();
};

});

First request with Chrome :

Request URL:https://remote.com/API/action.php
Request Method:OPTIONS
Status Code:200 OK

Second request with Chrome :

Request URL:https://remote.com/API/action.php
Request Method:POST
Status Code:200 OK

Request Headers

Accept:*/*
Accept-Encoding:gzip,deflate,sdch
Accept-Language:fr-FR,fr;q=0.8,en-US;q=0.6,en;q=0.4
Access-Control-Request-Headers:content-type
Access-Control-Request-Method:POST
Cache-Control:no-cache
Connection:keep-alive
Host:hipt.ucc.ie
Origin:http://server.com
Pragma:no-cache
Referer: XXX
User-Agent:Mozilla/5.0 (Windows NT 6.2; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/32.0.1700.107 Safari/537.36

Response Headers

Access-Control-Allow-Headers:Content-Type, Authorization, X-Requested-With
Access-Control-Allow-Methods:GET, PUT, POST, DELETE, OPTIONS
Access-Control-Allow-Origin:*
Access-Control-Max-Age:1000
Cache-Control:no-cache
Connection:close
Content-Length:5
Content-Type:text/html; charset=UTF-8
Date:Mon, 24 Feb 2014 11:57:54 GMT
Server:Apache/2.2.3 (CentOS)
X-Powered-By:PHP/5.1.6

Serverside script :

<?php

header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, PUT, POST, DELETE, OPTIONS');
header('Cache-Control: no-cache');
header('Access-Control-Max-Age: 1000');
header('Access-Control-Allow-Headers: Content-Type, Authorization, X-Requested-With');

if (!empty($_FILES)) {

With Firefox the response to the request with the OPTIONS method is empty and there is no following POST request.

Here are the Firefox headers:

Firefox headers

I cannot figure out why it is not working with Firefox and IE8.

Thanks for your help.

[EDIT] I just tried with flash runtimes: same thing it works with Chrome and IE 10 but not with Firefox and IE8. The weird thing is that the alert(info['runtime']); does not appear but there is no javascript error in the console...

Était-ce utile?

La solution 2

Ok so I finally find out why it wasn't working. I checked using wireshark and I noticed that there was an encrypted alert.

I then check the certificate of the remote server using : http://www.sslshopper.com/ssl-checker.html and got this answer :

The certificate is not trusted in all web browsers. You may need to install an Intermediate/chain certificate to link it to a trusted root certificate. Learn more about this error. The fastest way to fix this problem is to contact your SSL provider.

I had to add an exception and it finally worked \o/

Autres conseils

Usefull Links for Plupload crossdomain upload 200 http error :

1: http://weblog.west-wind.com/posts/2013/Mar/12/Using-plUpload-to-upload-Files-with-ASPNET

2: http://www.bennadel.com/blog/2502-Uploading-Files-To-Amazon-S3-Using-Plupload-And-ColdFusion.htm

3: http://www.plupload.com/punbb/viewtopic.php?id=4000

4: https://github.com/moxiecode/plupload/wiki/Frequently-Asked-Questions

plupload also sets a Content-Type header, so your server must also respond with Access-Control-Allow-Headers: Content-Type or else the OPTIONS request for CORS will fail.

If you need to debug this, the Web Inspector in Google Chrome does a fairly good job at pointing out which was the cause for your CORS request to fail.

This error is also raised when you get a server-side 500 error. For example, if you have a syntax error in your program (or a fatal run-time error).

I had the same problem, but I clearly knew that the problem was in csrf token. The solution is the following:

HTML:

<HTML>

<body>
<p>your template content</p>

<!-- upload demo -->
<ul id="filelist"></ul>
<br />
<pre id="console"></pre>
<div id="container">
<a id="browse" href="javascript:;">[Browse...]</a>
{% csrf_token %} <!-- it may be places elsewhere in HTML -->
<a id="start-upload" href="javascript:;">[Start Upload]</a>
</div>
<!-- upload demo end -->

<p>your template cont'd</p>

<script type="text/javascript">
// function to get your crsf token from the cookie
function getCookie(name) {
    let cookieValue = null;
    if (document.cookie && document.cookie !== '') {
        const cookies = document.cookie.split(';');
        for (let i = 0; i < cookies.length; i++) {
            const cookie = cookies[i].trim();
            // Does this cookie string begin with the name we want?
            if (cookie.substring(0, name.length + 1) === (name + '=')) {
                cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                break;
            }
        }
    }
    return cookieValue;
}

const crsf = getCookie('csrftoken');

var uploader = new plupload.Uploader({
    browse_button: 'browse', // this can be an id of a DOM element or the DOM element itself
    url: '/upload/',
   chunk_size: '822kb',
   headers: {'X-CSRFToken': crsf}, // here we add token to a header
   max_retries: 1
});
 
uploader.init();

<!-- and so on -->

</script>
</body>
</HTML>
#urls.py
urlpatterns = [
    ...
    path(route='upload/', view=Upload.as_view(), name='upload'),
#views.py
class Upload(View):

    def post(self, request):
        print('got upload post request')
        print(request.headers)
        ## do with the chunk whatever you need...
        return HttpResponse('email good, thank you!', status=200)    

The example from here: https://www.plupload.com/docs/v2/Getting-Started#wiki-full-example

And you may read about settings over here: https://www.plupload.com/docs/v2/Uploader#settings-property

It works with post() method in Django 2.1+

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top