dqhnp44220
2015-03-23 15:31 阅读 161

通过AJAX发送文件会返回“blob”错误

I'm trying to make an AJAX request send a file towards my controller, which then should proceed to read out the sent file and return a sorted array back to the front-end, though it doesn't work as I'm stuck on a 'blob' not set error. I've searched about but didn't really find the answer I was looking for, thus why I'm creating this question.

Currently I'm receiving the following TypeError:

'slice' called on an object that does not implement interface Blob.

The data that I'm trying to send is as following:

http://piclair.com/qk8ms (pic because I can't copy the data directly from my browser.)

The javascript:

// Click handler for file read
$(document).on('click','#load-csv-btn',function(e){
    e.preventDefault();
    var file = $('#file_upload')[0].files;
    console.log(file);

    readCSV(file);
});


function readCSV(file){
    $.ajax({
        type: "POST",
        url: "ajax/read.php",
        data: {file: file},
        contentType: false
    }).success(function(data){
        console.log(data);
    }).fail(function(){
        console.log('error');
    });
}

The PHP handler, though I guess that part is kind of irrelevant for this problem:

<?php
    var_dump($_POST);

I've found someone saying that setting processData: false and contentType: false would let the script ignore the blob requirment, but if I set those parameters my server just sends back an empty array, which I guess is no suprise as I'm not processing any data.

So I'm hoping someone knows a solution to this problem and is able to help me out.

EDIT:

Just to make clear which method I've tried that returns an empty array, here is the alternate code:

$(document).on('click','#load-csv-btn',function(e){
    e.preventDefault();
    var file = $('#file_upload')[0].files[0];
    var fd = new FormData();
    fd.append("csv",file);

    readCSV(fd);
});


function readCSV(file){
    $.ajax({
        type: "POST",
        url: "ajax/read.php",
        data: {file: file},
        contentType: false,
        processData: false
    }).success(function(data){
        console.log(data);
    }).fail(function(){
        console.log('error');
    });
}
  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享

1条回答 默认 最新

  • 已采纳
    douzi2778 douzi2778 2015-03-23 17:03

    As far as I am concerned AJAX uploads are not easily done without external libraries. At least, that is what I learned the first time I needed this done.

    http://www.9lessons.info/2011/08/ajax-image-upload-without-refreshing.html

    This guide is pretty good, but a little bit outdated if you are using a newer version of jQuery. You might need to change some deprecated functionality such as (.live() to .on()).

    In the end I can warmly recommend it as a good start. I've used it widely for years and with great success.

    Good luck!

    点赞 评论 复制链接分享

相关推荐