Jquery filupload给出错误JSON.parse:意外的数据结束

时间:2013-05-16 05:31:50

标签: amazon-s3 jquery-file-upload

我正在使用Jquery_fileupload(JFU)将文件发送到亚马逊s3存储桶。

当用户选择的文件时,文件自动上传成功,亚马逊返回状态代码204无内容。为了简单起见,我已经更改了s3策略以返回200代码。

问题是JFU为每个文件提供了一条错误消息,即使没有错误:

在firefox中它是:SyntaxError:JSON.parse:意外的数据结尾

在chrome中它是:SyntaxError:意外的输入结束

任何解决此问题的想法都会有所帮助。感谢

JFU设置:

    $(document).ready(function() {
      $('#fileupload').fileupload({
        dropZone: $('#dropzone'),
        autoUpload: true,
        paramName: 'file',
        singleFileUploads: false,
        limitMultiFileUploads: 1,
        sequentialUploads: true,
        multipart: true,
        uploadTemplateId: null,
        downloadTemplateId: null,
        filesContainer: $('#upload-files-container'),
        uploadTemplate: function (o) {
          var rows = $();
          $.each(o.files, function (index, file) {
            var row = $('<tr class="template-upload fade">' +
            '<td class="preview"><span class="fade"></span></td>' +
            '<td class="name"></td>' +
            '<td class="size"></td>' +
            (file.error ? '<td class="error" colspan="2"></td>' :
            '<td><div class="progress progress-info progress-striped active">' +
            '<div class="bar" style="width:0%;"></div></div></td>'
            ) + '<td class="cancel"><button class="btn btn-warning">Cancel</button></td></tr>');
            row.find('.name').text(file.name);
            row.find('.size').text(o.formatFileSize(file.size));
            if (file.error) {
              row.find('.error').text(
                locale.fileupload.errors[file.error] || file.error
              );
            }
            rows = rows.add(row);
          });
          return rows;
        },
        downloadTemplate: function (o) {
          var rows = $();
          $.each(o.files, function (index, file) {
            var row = $('<tr class="template-download">' +
            (file.error ? '<td></td><td class="name"></td>' +
            '<td class="size"></td><td class="error" colspan="2"></td>' :
            '<td class="preview"></td>' +
            '<td class="name"><a></a></td>' +
            '<td class="size"></td><td colspan="2"></td>'
            ) + '</tr>');
            row.find('.size').text(o.formatFileSize(file.size));
            if (file.error) {
              row.find('.name').text(file.name);
              row.find('.error').text(
                locale.fileupload.errors[file.error] || file.error
              );
            } else {
              row.find('.name a').text(file.name);
              if (file.thumbnail_url) {
                row.find('.preview').append('<a><img></a>')
                .find('img').prop('src', file.thumbnail_url);
                row.find('a').prop('rel', 'gallery');
              }
              row.find('a').prop('href', file.url);
            }
            rows = rows.add(row);
          });
          return rows;
        }
      })
    });

S3政策数据如果有帮助:

def policy_data
  {
    expiration: @options[:expiration],
    conditions: [
      ["starts-with", "$utf8", ""],
      ["starts-with", "$key", ""],
      ["content-length-range", 0, @options[:max_file_size]],
      {bucket: @options[:bucket]},
      {acl: @options[:acl]},
      {success_action_status: "200"}
    ]
  }
end

3 个答案:

答案 0 :(得分:1)

同样,我发现Jquery_fileupload'失败'是因为格式化的json响应不正确 - 无论是浏览器问题还是S3,我都不知道。该文件实际上传得很好,但无效的json会抛出错误。

无论如何,我通过设置JFU option

来修复它
dataType: 'xml'

然后将响应从xml转换为json。 (为此我使用了x2js库。)

这是我的AngularJS'fileuploaddone'监听器:

$scope.$on('fileuploaddone', function(e, data) {
  var response;
  response = x2js.xml2json(data.result);
  $scope.file_url = response != null ? (_ref = response.PostResponse) != null ? _ref.Location : void 0 : void 0;
});

答案 1 :(得分:0)

将xml转换为json就可以了。 在阅读了1ththhershers的回答后,我最终得到了以下解决方案:

function uploaderReady(){
  if($('#fileupload').length){
    // // Initialize the jQuery File Upload widget:
    $('#fileupload').fileupload({
      //forceIframeTransport: true,    // DO NOT SET: https://github.com/blueimp/jQuery-File-Upload/issues/1803
      dropZone: $('#dropzone'),
      autoUpload: true,
      paramName: 'file',
      dataType: 'xml', // S3 returns xml, so expect xml in return
      singleFileUploads: false,
      limitMultiFileUploads: 1,
      sequentialUploads: true,
      multipart: true,
      uploadTemplateId: null,
      downloadTemplateId: null,
      filesContainer: $('#upload-files-container'),
      add: function (e, data) {
        var $this = $(this),
        that = $this.data('blueimp-fileupload') ||
        $this.data('fileupload'),
        options = that.options,
        files = data.files;
        data.process(function () {
          return $this.fileupload('process', data);
        }).always(function () {
          data.context = that._renderUpload(files).data('data', data);
          that._renderPreviews(data);
          options.filesContainer[
          options.prependFiles ? 'prepend' : 'append'
          ](data.context);
          that._forceReflow(data.context);
          that._transition(data.context).done(
            function () {
              if ((that._trigger('added', e, data) !== false) &&
              (options.autoUpload || data.autoUpload) &&
              data.autoUpload !== false && !data.files.error) {
                //check file size, if less than 2mb, upload to heroku, otherwise direct to amazon.
                var form = $('#fileupload');
                if(data.files[0].size < 2097152){
                  form.attr('action', form.data('local-url'));
                }else{
                  form.attr('action', form.data('external-url'));
                }
                data.submit();
              }
            }
          );
        });
      },
      uploadTemplate: function (o) {
        var rows = $();
        $.each(o.files, function (index, file) {
          var row = $('<tr class="template-upload fade">' +
          '<td class="preview"><span class="fade"></span></td>' +
          '<td class="name"></td>' +
          '<td class="size"></td>' +
          (file.error ? '<td class="error" colspan="2"></td>' :
          '<td><div class="progress progress-info progress-striped active">' +
          '<div class="bar" style="width:0%;"></div></div></td>'
          ) + '<td class="cancel"><button class="btn btn-warning">Cancel</button></td></tr>');
          row.find('.name').text(file.name);
          row.find('.size').text(o.formatFileSize(file.size));
          if (file.error) {
            row.find('.error').text(
              file.error
            );
          }
          rows = rows.add(row);
        });
        return rows;
      },
      downloadTemplate: function (o) {
        var rows = $();
        $.each(o.files, function (index, file) {
          var row = $('<tr class="template-download">' +
          (file.error ? '<td></td><td class="name"></td>' +
          '<td class="size"></td><td class="error" colspan="2"></td>' :
          '<td class="preview"></td>' +
          '<td class="name"><a></a></td>' +
          '<td class="size"></td><td colspan="2"></td>'
          ) + '</tr>');
          row.find('.size').text(o.formatFileSize(file.size));
          if (file.error) {
            row.find('.name').text(file.name);
            row.find('.error').text(
              file.error
            );
          } else {
            row.find('.name').text(file.name);
            if (file.thumbnailUrl) {
              row.find('.preview').append('<a><img></a>')
              .find('img').prop('src', file.thumbnailUrl);
              row.find('a').prop('rel', 'gallery');
            }
            row.find('.size').text( (file.size/1024).toFixed(2)+' KB');
            row.find('a').prop('href', file.url);
          }
          rows = rows.add(row);
        });
        return rows;
      }
    });
    $('#fileupload').bind('fileuploaddone', function (e, data){
      var response = $(data.jqXHR.responseText);
      if(data.jqXHR.status == 201 && response.find('Key').text() != ''){
        // amazon solution
        data.result = data;
      }else{
        // local solution
        data.result = {'files': [{
        'name': response.find('name').text(),
        'size': response.find('size').text(),
        'type': response.find('type').text(),
        'url': response.find('url').text(),
        'thumbnailUrl': response.find('thumbnailUrl').text()
        }]}
      }
    }); //end fileuploader
  }
}
$(document).ready(uploaderReady);
$(document).on('page:load', uploaderReady);

答案 2 :(得分:0)

对于那些遇到此问题的人(就像我一样)假设你已经解决了所有典型的陷阱/错误,剩下的就是浏览器的安全性。

  • 确保您正在制作正确的json与jsonp请求
  • 并检查访问控制源(如果适用)