2016-08-18 172 views
1

我在我的rails应用程序中使用shrine gem来进行文件上传。我想将这个gem与fineuploader前端库集成,以在上传文件的同时增强用户体验。我可以将它集成到我能够通过fineuploader前端通过神龛服务器端代码将文件上传到我的s3存储桶。自定义神社宝石JSON响应

现在,在成功上载我收到JSON响应200个状态码,出现类似以下内容:

{"id":"4a4191c6c43f54c0a1eb2cf482fb3543.PNG","storage":"cache","metadata":{"filename":"IMG_0105.PNG","size":114333,"mime_type":"image/png","width":640,"height":1136}} 

但fineuploader预计JSON响应与true值的success属性,以考虑这个反应成功。所以我需要修改这个200状态JSON响应来插入这个成功的属性。对于这一点,我问shrine宝石的作者,他劝我在神社初始化文件中使用此代码:通过使用此代码fineuploader

class FineUploaderResponse 
    def initialize(app) 
    @app = app 
    end 

    def call(env) 
    status, headers, body = @app.call(env) 

    if status == 200 
     data = JSON.parse(body[0]) 
     data["success"] = true 
     body[0] = data.to_json 
    end 

    [status, headers, body] 
    end 
end 

Shrine::UploadEndpoint.use FineUploaderResponse 

不幸的是,这个代码不工作,INFACT抛出以下控制台错误:

Error when attempting to parse xhr response text (Unexpected end of JSON input) 

请咨询我,我该怎么需要修改这个代码中插入success财产与一个有效的JSON响应。

+0

您是否找到了解决方案? – Robin

回答

2

更改主体后,需要更新标头中的Content-Length,否则浏览器将会将其关闭。如果你这样做,它将完美地工作:

class FineUploaderResponse 
    def initialize(app) 
    @app = app 
    end 

    def call(env) 
    status, headers, body = @app.call(env) 

    if status == 200 
     data = JSON.parse(body[0]) 
     data['success'] = true 
     body[0] = data.to_json 

     # Now let's update the header with the new Content-Length 
     headers['Content-Length'] = body[0].length 
    end 

    [status, headers, body] 
    end 
end 

Shrine::UploadEndpoint.use FineUploaderResponse