Почему при запуске загрузки я получаю неопределенный тип из внутренних структур JQuery File-Upload?

Я начал с руководства по загрузке файлов из Heroku. Я получил много базовых работ, а затем начал настраивать его в соответствии с моим реальным сценарием использования и желаниями.

Одна из важных вещей, которые мне не нравятся в простой версии heroku, заключается в том, что она использует предварительно назначенные URL-адреса без достаточно короткого срока действия. Хотя это не явное нарушение безопасности, оно все же меня не устраивало. Поэтому я начал взламывать, понимать, что делается, и "исправлять" это. (Это также отправная точка для других исправлений)

Я почти у цели, но я застрял в самой важной части: загрузка не сработает. Я попробовал несколько методов, и следующий код может быть немного грязным, но он должен передать то, что я пытаюсь:

// 1.  When user selects a file, prepare controls to allow upload
// 2.  When user hits 'submit', fetch the presigned url to allow uploading
// 3.  Once presigned url is available, initiate upload <-- broken
// 4.  Provide UI feedback on upload status
// 5.  TODO, but inform rails of upload and update model accordingly

var submitMethod;

$(function() {
  // bind necessary code to the html elements
  var uploadField = $('#PackageFileUploadControls input:file')
  uploadField.fileupload({
    type: 'POST',
    autoUpload: false,
    paramName: 'file',
    dataType: 'XML',
    replaceFileInput: false,
    fileInput:uploadField,
    add: fileAddedToUploader,
    progressall: uploadProgress,
    fail: uploadFail,
    done: uploadComplete
  });
  $('#PackageFileUploadControls button').click(uploadClicked)
});

// when files are added to the uploader, enable the upload button
// and store the submit method for later use
var fileAddedToUploader = function(e, data){
  button = $('#PackageFileUploadControls button');
  button.removeClass('disabled');
  submitMethod = data.submit;
  console.log(submitMethod);
}

//Handle progress updates
var uploadProgress = function(e, data){
  var progress = parseInt(data.loaded / data.total * 100, 10);
  progressBar.css('width', progress + '%')
}

//in event of an upload failure, report it, reset controls
var uploadFail = function(e, data){
  console.log("upload failure", e, data);
  resetUploadControls();
  alert("Error uploading file, refresh and try again.");
}

// Pending more details, but successful upload complete
var uploadComplete = function(e, data){
  var key   = $(data.jqXHR.responseXML).find("Key").text();
  alert("upload complete!  Key is: " + key)
}

// the upload button has been clicked.  Start the upload
var uploadClicked = function(){
  var uploadField = $('#PackageFileUploadControls input:file')
  uploadField.addClass('hide');
  $('#PackageFileUploadControls button').addClass('disabled');
  $('#FileName').removeClass('hide')
  $('#PackageFileUploadStatus').removeClass('hide')
  $.get('presigned_upload_key')
    .done(recieved_presigned_url)
    .fail(presigned_url_failed);
}

// We need to fetch the presigned url.  This method is called
// when the get AJAX call succeeds
var recieved_presigned_url = function(data){
  var uploadField = $('#PackageFileUploadControls input:file')
  uploadField.fileupload('option', 'url', data.presigned_url.url);
  uploadField.fileupload('option', 'formData', data.presigned_url.fields);
  button = $('#PackageFileUploadControls button');
  console.log(button.data.startMethod);
  console.log(submitMethod);
  submitMethod(); //<-- Crashes app
}

// We need to fetch the presigned url.  This method is called
// when the get AJAX call fails
var presigned_url_failed = function(error){
  resetUploadControls();
  alert("Error uploading file, refresh and try again.");
}

// DRY -- called from multiple places to reset controls to pre-upload state
var resetUploadControls = function(){
  uploadField.removeClass('hide');
  $('#PackageFileUploadControls button').removeClass('disabled');
  $('#FileName').addClass('hide')
  $('#PackageFileUploadStatus').addClass('hide')
}

Я получаю крушение Uncaught TypeError: Cannot read property 'state' of undefinedи я начал копаться

Я путаюсь с тем, что "это" должно, как я думал, быть зафиксировано автоматически при определении функции. В противном случае это вообще не должно работать.

        data.submit = function () {
            if (this.state() !== 'pending') {
                data.jqXHR = this.jqXHR =
                    (that._trigger(
                        'submit',
                        $.Event('submit', {delegatedEvent: e}),
                        this
                    ) !== false) && that._onSend(e, this);
            }
            return this.jqXHR || that._getXHRPromise();
        };

0 ответов

Другие вопросы по тегам