使用法拉第上传图像文件作为Zendesk评论的附件

时间:2017-11-24 02:32:48

标签: ruby-on-rails image-uploading multipart zendesk faraday

我能够同时提交故障单和文件附件,但当我尝试使用图像查看器打开上传的图像时出现此错误

Error interpreting JPEG image file (Not a JPEG file: starts with 0x2d 0x2d)

和我上传时的控制台输出显示

Content-Type: "multipart/form-data;

这是我提交图片的方式,我用HAML表单上传

connection = Faraday.new(:url => "https://account.zendesk.com/api/v2/uploads.json?filename=image.jpg") do |builder|
  builder.basic_auth "email/token", "token"
  builder.request :multipart
  builder.response :logger
  builder.adapter Faraday.default_adapter
end

payload = { 'files[]' => Faraday::UploadIO.new(open(params["images"].first).path, 'image/jpg', "image.jpg", "Content-Disposition" => "file") }
response = connection.post do |req|
  req.body = payload
  req.headers['Accept'] = 'application/json'
end
rtn_data = JSON.load(response.body)

token = rtn_data['upload']['token']

获得令牌后,我按照以下方式提交票证:

conn = Faraday.new :url => "https://account.zendesk.com/api/v2/tickets/#{params["ticket_id"]}.json"
    conn.basic_auth "email/token", "token"
    resp = conn.put do |req|
      req.headers['Accept'] = 'application/json'
      req.headers['Content-Type'] = 'application/json'
      req.body =
      '{
        "ticket": {
          "comment": {
            "body": "See screenshot.",
            "uploads":["' + token + '"]
          }
        }
      }
    end

如果我尝试将文件上传的内容类型更改为

req.headers['Content-Type'] = 'image/jpg'

我收到错误

undefined method 'bytesize' for Hash:0x007fb11e104b78

如果我然后将路径更改为.to_json

Faraday::UploadIO.new(open(params["images"].first).path.to_json, 'image/jpg', "image.jpg", "Content-Disposition" => "file") }

我收到了另一个错误

  

没有这样的文件或目录@ rb_sysopen -   " /tmp/RackMultipart20171124-15501-1n0qio6.jpg"

但如果我在浏览器中粘贴路线 - 图片会加载。 知道我做错了什么吗?

0 个答案:

没有答案