2015-08-28 37 views
1

我有一個用rails完成的API。我正在尋找在同一個POST請求中上傳多個文件。我想知道是否只有通過使用表單數據(例如mention here)才能做到這一點?將上傳的文件序列化並嵌入到JSON中

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' 

感謝

+0

爲什麼你關心這個問題?你可以對你的文件進行手動序列化/反序列化,但爲什麼瀏覽器和Rails會用'multipart/form-data'來爲你做這件事。 – EugZol

+0

因爲目前我的所有api都是json api,所以我必須編寫藍圖文檔。目前我必須做那樣的事情。 https://github.com/apiaryio/api-blueprint/issues/100#issuecomment-48290545 – Mio

回答

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,使串行器爲您平臺。數據URL只是data:[<MIME-type>][;charset=<encoding>][;base64],<data>source

在您的服務器端:

最有可能你不需要做任何事情,因爲回形針/ carrierwave將反序列化的東西給你。

+0

謝謝@EugZol! – Mio

+0

不客氣! – EugZol