javascript - 如何通过主干接收图像?

标签 javascript json cakephp backbone.js ripple

我正在尝试通过主干网从服务器接收图像。后端应用程序使用 CakePHP(我认为目前这并不重要)。后端返回一个 JSON 响应:

{"id":"4","waypoint_id":"56","user_id":"1","name":"Penguins.jpg","type":"image\/jpeg","size":"777835","created":"2014-03-10 18:05:29","modified":"2014-03-10 18:05:29","owner":"Nikel Weis"}

到目前为止,这很好 - 但一旦我添加包含数据库中实际 blob 的数据属性,它就不起作用。我尝试将其编码为 base64 字符串(在 php 中):

$response['data'] = base64_encode($response['data']);

但随后客户端返回:

OPTIONS http://mytour.localhost/api/file/4 No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:4400' is therefore not allowed access.

但是标题已设置。我的主干文件模型看起来像(非常简单):

define([
    'jquery',
    'jqm',
    'underscore',
    'backbone',
], function($, jqm, _, Backbone) {

File = Backbone.Model.extend({

    idAttribute: 'id',

    urlRoot: '/api/file',

    initialize:function(attributes, options) {
    },  

});

return File;
});

那么我如何使用backbone接收(base64编码的)文件?或者我的方法在这里完全错误?

编辑: 发送 header :

$this->response->header('Access-Control-Allow-Origin', '*');
$this->response->header('Access-Control-Allow-Headers', 'X-Requested-With');

当 base64 编码的字符串不存在时,我能够收到响应。

编辑 - 解决方案: 我应该提到的是,我正在使用ripple 来模拟phonegap 环境。现在我明白了几件事:

  1. 问题不在于 Base64 编码 - 当字符串超过大约 4000 个字符时就会出现问题。来自服务器的响应未被ripple正确处理。

  2. Ripple 具有代理跨域请求的功能。我已经关闭了该代理。通过将代理切换到本地或远程,JSON 响应中约 4000 个字符的限制不会生效。这不是 JSON 或其他什么的缺点,因为传回客户端的字符串没有限制。

最佳答案

$this->response->header("Access-Control-Allow-Methods", "POST, PUT, GET, DELETE, HEAD, OPTIONS");

阅读here ,用 php 代码进行了很好的解释。除此之外...阅读 CakePHP 安全 doc 。我知道一些框架空白选项请求上的 CSRF token 。最后要尝试的是创建一个纯 PHP 代码来处理请求,并查看 CakePHP 是否确实阻止了请求。

关于javascript - 如何通过主干接收图像?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22325802/

相关文章:

cakephp - 如何使用cakephp在url中传递数据?

javascript - 需要在 ng-template 中解释 let-* 指令

javascript - 如何使用 array-contains 作为包含 map 的数组

javascript - Vuejs : how do you pass class(classes) to template?

python - 在 pandas 中使用 to_json 时如何保留 DataFrame 索引名称?

python - 如何避免自动更改panda dataframe中的数据类型并在python中转换为CSV?

php - CakePhp 中的严格标准错误?

mysql - 数据库中的多个项目

java - Action 类无法从 jsp 获取更改的值

json - 从 UI 写入数据库之前进行检查