ruby-on-rails - 将文件发送到 Rails JSON API

我知道有类似的问题,但我还没有找到一个好的答案。我需要做的是将一个对象的描述发送到我的一个创建方法,其中包括一些不同的属性,包括一个名为 :image 的属性,一个回形针附件:

has_attached_file :image

现在我读到可以通过将图像编码和解码为 base64 直接在 JSON 中完成发送图像,但这对我来说感觉像是一个肮脏的解决方案。一定有更好的办法。

另一种解决方案是发送 multipart/form-data 请求,很像 LEEjava describes here.问题在于 Rails 3.2.2 中的请求参数未正确解释,并且 JSON.parse 在尝试解析参数时会吐出错误,或者可能是 Rails 误解了某些内容。

Started POST "/api/v1/somemodel.json?token=ZoipX7yhcGfrWauoGyog" for 127.0.0.1 at 2012-03-18 15:53:30 +0200 Processing by Api::V1::SomeController#create as JSON Parameters: {"{\n
\"parentmodel\": {\n \"superparent_id\": 1,\n
\"description\": \"Enjoy the flower\",\n \"\": "=>{"\n
{\n \"someattribute\": 1,\n
\"someotherattribute\": 2,\n \"image\": \"image1\"\n
}\n "=>{"\n }\n}"=>nil}}, "token"=>"ZoipX7yhcGfrWauoGyog"}

很难读懂,抱歉。 JSON.parse(params[:parentmodel]) 在这里是不可能的,我也不能 JSON.parse(params) 因为 token 属性,JSON.parse(params) 会抛出这个错误:

TypeError (can't convert ActiveSupport::HashWithIndifferentAccess into String)

这让我相信我要么完全错误地解决了这个问题,要么我只是在做某事。无论哪种方式,我们都可以确定我错了。 :)

有没有更好的方法来做到这一点?有人可以向我指出任何指南/教程,或者写一个答案来描述我应该如何处理这个问题吗?

提前谢谢你

更新: 所以我现在实际上已经让它工作了,但只是在测试中。我不完全确定这是如何工作的,但也许有人可以为我填补空白?这是测试代码的一部分(图片:fixture_file_upload(...) 是重要的部分)。

parts_of_the_object = { someattribute: 0, someotherattribute: 0, image: fixture_file_upload('/images/plot.jpg', 'image/jpg') }

我的 params[] 看起来像是提交了一个普通的 HTML 表单,这很奇怪(而且很棒):

Parameters: {"superparentid"=>"1", "plots"=>[{"someattribute"=>"0", "someotherattribute"=>"0", "image"=>#<ActionDispatch::Http::UploadedFile:0x007f812eab00e8 @original_filename="plot.jpg", @content_type="image/jpg", @headers="Content-Disposition: form-data; name=\"plots[][image]\"; filename=\"plot.jpg\"\r\nContent-Type: image/jpg\r\nContent-Length: 51818\r\n", @tempfile=#<File:/var/folders/45/rcdbb3p50bl2rgjzqp3f0grw0000gn/T/RackMultipart20120318-1242-1cn036o>>}], "token"=>"4L5LszuXQMY6rExfifio"}

请求就像使用 rspec 发出请求一样:

post "/api/v1/mycontroller.json?token=#{@token}", thefull_object

所以我已经完成了所有工作。我只是不知道它是如何工作的!我也希望能够自己创建这样的响应,而不仅仅是来自 RSpec。 :-)

最佳答案

昨天我实际上在这个问题上度过了一段糟糕的时光,做了一些非常相似的事情。事实上,我写了这个问题:Base64 upload from Android/Java to RoR Carrierwave

归根结底是在 Controller 中创建上传的图像对象,然后将其注入(inject)回参数中。

对于这个特定的示例,我们正在获取一个 base64 文件(我假设您有,因为 JSON 不支持嵌入文件)并将其保存为系统中的临时文件,然后我们正在创建 UploadedFile 对象并最终重新注入(inject)它进入参数。

我的 json/params 是什么样的:

picture {:user_id => "1", :folder_id => 1, etc., :picture_path {:file => "base64 awesomeness", :original_filename => "my file name", :filename => "my file name"}}

这是我的 Controller 现在的样子:

  # POST /pictures
  # POST /pictures.json
  def create

    #check if file is within picture_path
    if params[:picture][:picture_path]["file"]
         picture_path_params = params[:picture][:picture_path]
         #create a new tempfile named fileupload
         tempfile = Tempfile.new("fileupload")
         tempfile.binmode
         #get the file and decode it with base64 then write it to the tempfile
         tempfile.write(Base64.decode64(picture_path_params["file"]))

         #create a new uploaded file
         uploaded_file = ActionDispatch::Http::UploadedFile.new(:tempfile => tempfile, :filename => picture_path_params["filename"], :original_filename => picture_path_params["original_filename"]) 

         #replace picture_path with the new uploaded file
         params[:picture][:picture_path] =  uploaded_file

    end

    @picture = Picture.new(params[:picture])

    respond_to do |format|
      if @picture.save
        format.html { redirect_to @picture, notice: 'Picture was successfully created.' }
        format.json { render json: @picture, status: :created, location: @picture }
      else
        format.html { render action: "new" }
        format.json { render json: @picture.errors, status: :unprocessable_entity }
      end
    end
  end

此时剩下要做的就是删除临时文件,我相信这可以通过 tempfile.delete

我希望这对您的问题有所帮助!我昨天花了一整天的时间寻找解决方案,而我所看到的一切都是死胡同。但是,这适用于我的测试用例。

https://stackoverflow.com/questions/9758879/

相关文章:

c# - 反序列化期间的 JSON.Net Ignore Property

json - 浏览器 JSON 插件

python - 无法解析 JSON 文件中的 TAB

javascript - 如何在不解析的情况下在javascript中同步包含JSON数据?

javascript - 未捕获的类型错误 : Cannot read property 'prop

java - 在spring-mvc中将json解析为java对象

json - 将 JSON 与 LogStash 一起使用

json - 如何解析 JSON 文件?

json - Jackson:有没有办法将 POJO 直接序列化为 treemodel?

c# - 使 ASP.NET WCF 将字典转换为 JSON,省略 "Key"和 "Value"标记