【问题标题】:Parse get image file data from url and save it as a Parse FileParse 从 url 获取图像文件数据并保存为 Parse File
【发布时间】:2017-02-25 21:14:41
【问题描述】:

我正在尝试使用 Ajax 获取图像文件,然后将其保存为解析文件。我是这个过程的新手,这就是我到目前为止所得到的:

$.ajax({
        type: "GET",
        url: url,
        headers:{'Content-Type':'image/jpeg','X-Requested-With':'XMLHttpRequest'},
        processData: false,
        success: function (data) {

            var name = "photo.jpg";
            var img = btoa(encodeURIComponent(data));

            var parseFile = new Parse.File(name, { base64: img });

            parseFile.save().then(function () {

                console.log('Saved parse file: ' + parseFile.url());

            }, function (error) {

                console.log("error: " + error.message);
            });
        },
        error: function (xhr, ajaxOptions, thrownError) {

            console.log('error on uploadPhoto: ' + xhr + ' ' + ajaxOptions + ' ' + thrownError);
        }
    });

文件似乎已保存,但我得到的只是一个空文件。 Parse Docs 说我们可以使用 base64 编码的字符串或字节值数组。

我做错了什么,有更好的方法吗?

【问题讨论】:

    标签: javascript ajax parse-platform parse-server


    【解决方案1】:

    我决定使用一种不同的方法来使用 XMLHttpRequest。代码如下:

    var xhr = new XMLHttpRequest();
        xhr.onreadystatechange = function () {
    
            if (this.readyState == 4 && this.status == 200) {
    
                var reader = new window.FileReader();
    
                reader.readAsDataURL(this.response);
    
                reader.onloadend = function () {
    
                    var name = "photo.jpg";
    
                    var base64data = reader.result;
    
                    var parseFile = new Parse.File(name, {base64: base64data});
    
                    parseFile.save().then(function () {
    
                        console.log('Saved parse file: ' + parseFile.url());
    
                    }, function (error) {
    
                        console.log("error: " + error.message);
                    });
                }
            }
        };
    
        xhr.open('GET', url);
        xhr.responseType = 'blob';
        xhr.send();
    

    现在文件被正确保存为解析文件。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-02-21
      相关资源
      最近更新 更多