[英]Customize Shrine gem JSON response
I'm using shrine
gem in my rails app for for file uploading. 我正在Rails应用程序中使用
shrine
gem进行文件上传。 I want to integrate this gem with fineuploader front-end library to enhance the user experience while uploading the files. 我想将此gem与fineuploader前端库集成在一起,以在上传文件时增强用户体验。 I'm able to integrate it to an extent that I'm able to upload files through fineuploader front-end via shrine server-side code to my s3 bucket.
我能够将其集成到某种程度,以便能够通过shine服务器端代码通过fineuploader前端将文件上传到我的s3存储桶。
Now, on a successful upload I receive a 200 status code with JSON response which appear something like following: 现在,在成功上传后,我会收到带有JSON响应的200状态代码,如下所示:
{"id":"4a4191c6c43f54c0a1eb2cf482fb3543.PNG","storage":"cache","metadata":{"filename":"IMG_0105.PNG","size":114333,"mime_type":"image/png","width":640,"height":1136}}
But the fineuploader expects a success
property in JSON response with a value of true
in order to consider this response successful. 但是fineuploader期望JSON响应中的
success
属性值为true
,以便将该响应视为成功。 So I need to modify this 200 status JSON response to insert this success property. 因此,我需要修改此200状态JSON响应以插入此成功属性。 For this, I asked the author of
shrine
gem and he advised me to use this code in shrine initializer file: 为此,我问了
shrine
gem的作者,他建议我在神社初始化文件中使用以下代码:
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
Unfortunately, this code is not working and infact by using this code fineuploader is throwing following error in console: 不幸的是,此代码无法正常工作,并且通过使用以下代码而无法正常工作:fineuploader在控制台中引发以下错误:
Error when attempting to parse xhr response text (Unexpected end of JSON input)
Please advice me, how I need to modify this code to insert success
property with a valid JSON response. 请告诉我,我如何需要修改此代码以使用有效的JSON响应插入
success
属性。
After you change the body, you need to update the Content-Length
within header or the browser will cut it off. 更改正文后,您需要更新标头中的
Content-Length
,否则浏览器将其切断。 If you do this, it will work flawlessly: 如果执行此操作,它将可以正常工作:
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.