序列化并将上载的文件嵌入到JSON中

时间:2015-08-28 13:17:03

标签: ruby-on-rails json curl

我使用rails完成了API。我想在同一个POST请求中上传多个文件。我想知道是否只使用像mention here这样的表单数据来做到这一点?

curl -X PATCH -H "Content-Type: multipart/form-data" -F "post[name]=wef" -F "post[catchphrase]=rteh reth erth erth" -F "post[posts_ids][]=8940" -F "post[screenshot1]=Ca9.png" -F "post[banner]=C34.png" -F  "post[icon]=60eb.jpg" 'http://example.com:3000/api/v1/5282/posts/111605.json?api_key=2s4ctv21vudsgreeegrge'

由于

1 个答案:

答案 0 :(得分:1)

您可以使用base64编码。

在您的客户端:

HTML

<input type="file" onchange="previewFile()"><br>
<img src="" height="200" alt="Image preview...">

的Javascript

function previewFile() {
  var preview = document.querySelector('img');
  var file    = document.querySelector('input[type=file]').files[0];
  var reader  = new FileReader();

  reader.onloadend = function () {
    preview.src = reader.result;
  }

  if (file) {
    reader.readAsDataURL(file);
  } else {
    preview.src = "";
  }
}

来源:readAsDataURL documentation

如果您不使用Javascript,请为您的平台制作序列化程序。数据网址仅为data:[<MIME-type>][;charset=<encoding>][;base64],<data>source

在您的服务器端:

很可能你根本不需要做任何事情,因为paperclip / carrierwave会为你反序列化这些东西。