简体   繁体   中英

Customize Shrine gem JSON response

I'm using shrine gem in my rails app for for file uploading. I want to integrate this gem with fineuploader front-end library to enhance the user experience while uploading the files. 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.

Now, on a successful upload I receive a 200 status code with JSON response which appear something like following:

{"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. So I need to modify this 200 status JSON response to insert this success property. For this, I asked the author of shrine gem and he advised me to use this code in shrine initializer file:

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:

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.

After you change the body, you need to update the Content-Length within header or the browser will cut it off. 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM