使用Signed_URL Google Storage进行JQuery-File-Upload,如何在Ajax回调中调用超类函数data.submit()?

问题描述 投票:1回答:1

我在DOM中有一个fileupload HTML元素,它当前获取多个文件,并为每个文件调用“添加”功能。对于每个文件,都会从对相关api的ajax调用中接收签名的URL。在成功调用api后,我想调用父函数的data.submit()方法,该方法是fileupload方法中的函数作为第一个参数。

[我如何才能在“ xhr.setRequestHeader('Content-Type',file.type);”之后访问它? ?

主要灵感来自此链接:http://kevindhawkins.com/blog/django-javascript-uploading-to-google-cloud-storage/

$("#fileupload").fileupload({
dataType: 'json',
sequentialUploads: true,

add: function(e, data) {
    $.each(data.files, function(index, file) {
        // pack our data to get signature url
        var formData = new FormData();
        formData.append('filename', file.name);
        formData.append('type', file.type);
        formData.append('size', file.size);

        // Step 3: get our signature URL
        $.ajax({
            url:  '/api/getsignedurl/',
            type: 'POST',
            processData: false,
            contentType: false,
            dataType: 'json',
            headers: {
                'X-CSRFToken': Cookies.get('csrftoken'),
            },
            context: 'hello',
            data: formData,
        }).done(function (data) {
            // Step 5: got our url, push to GCS
            const xhr = new XMLHttpRequest();
            if ('withCredentials' in xhr) {
                xhr.open("PUT", data.signed_url, true);
            }
            else if (typeof XDomainRequest !== 'undefined') {
                xhr = new XDomainRequest();
                xhr.open("PUT", data.signed_url);
            }
            else {
                xhr = null;
            }

            xhr.onload = () => {
                const status = xhr.status;
                if (status === 200) {
                    //alert("File is uploaded");
                } else {
                }
            };

            xhr.onerror = () => {
            };

            xhr.setRequestHeader('Content-Type', file.type);
            //data.submit();

        });
    });
},
django ajax google-cloud-storage jquery-file-upload pre-signed-url
1个回答
0
投票

如果$ this = $(this)在$ .each循环之前定义:

submit: function(e, data) {
    var $this = $(this);
    $.each(data.files, function(index, file) { ...

然后可以使用以下内容访问父函数中的数据

    this.primary_data.headers={'Content-Type': file.type};
    this.primary_data.jqXHR = $this.fileupload('send', this.primary_data);
© www.soinside.com 2019 - 2024. All rights reserved.