我想将文件从
Android客户端上传到Rails JSON API服务器.
我从Android客户端发送一个Multipart / form请求,看起来像这样:
Content-Type: multipart/form-data; boundary=d99ArGa2SaAsrXaGL_AdkNlmGn2wuflo5 Host: 10.0.2.2:3000 Connection: Keep-Alive User-Agent: Apache-HttpClient/UNAVAILABLE (java 1.4) --d99ArGa2SaAsrXaGL_AdkNlmGn2wuflo5 Content-Disposition: form-data; name="POSTDATA" Content-Type: application/json; charset=UTF-8 Content-Transfer-Encoding: 8bit {"tags":["test"],"location_id":1,"post":{"content":"test"}} --d99ArGa2SaAsrXaGL_AdkNlmGn2wuflo5 Content-Disposition: form-data; name="IMAGEDATA"; filename="testimage.jpg" Content-Type: image/jpeg Content-Transfer-Encoding: binary <BINARY DATA? --d99ArGa2SaAsrXaGL_AdkNlmGn2wuflo5--
在rails控制器中,我用这段代码创建了新的帖子:
@parsed_json = JSON(params[:POSTDATA]) @post = @current_user.posts.new(@parsed_json["post"])
如何使Paperclip从多部分表单保存附件?
我可以这样做:
if params.has_key?(:IMAGEDATA) photo = params[:IMAGEDATA] photo.rewind @filename = "/tmp/tempfile" File.open(@filename,"wb") do |file| file.write(photo.read) end @post.photo = File.open(@filename) end
解决方法
纯json的方法是不通过content-type multipart-form并将该文件作为base64编码的字符串传递给json.
我想这个感谢这篇文章:http://www.rqna.net/qna/xyxun-paperclip-throws-nohandlererror-with-base64-photo.html
以下是json的一个例子:
"{\"account\":{\"first_name\":\"John\",\"last_name\":\"Smith\",\"email\":\"john@test.com\",\"password\":\"testtest\",\"avatar\":{\"data\":\"INSERT BASE64 ENCODED STRING OF FILE HERE\",\"filename\":\"avatar.jpg\",\"content_type\":\"image/jpg\"}}}"
然后在控制器进程中@R_575_301@之前像这样的传入头像.
def process_avatar if params[:account] && params[:account][:avatar] data = StringIO.new(Base64.decode64(params[:account][:avatar][:data])) data.class.class_eval { attr_accessor :original_filename,:content_type } data.original_filename = params[:account][:avatar][:filename] data.content_type = params[:account][:avatar][:content_type] params[:account][:avatar] = data end end