How to upload image from iOS using Swift to a Ruby/Rails server -
i have ruby/rails application want accept image upload in base64 format inside of json request payload. basic app structure follows:
import uikit import mapkit class newcafedetailstableviewcontroller: uitableviewcontroller, nsurlconnectiondatadelegate { @iboutlet weak var submitbutton: uibutton! @iboutlet weak var mainimagecell: addimagecell! var submitdata: dictionary<string, anyobject>! override func viewdidload() { submitdata = ["name": "brian"] submitbutton.addtarget(self, action: selector("submit"), forcontrolevents: uicontrolevents.touchupinside) } func submit() { // i\'ve tried submit dynamic image, switched // hard-coded 1x1 gif grip on how on // backend before attempting more submitdata["thumbnail_data"] = "data:image/gif;base64,r0lgodlhaqabaiaaaaaaap///yh5baeaaaaalaaaaaabaaeaaaibraa7" var error: nserror? var submitjson: nsdata! submitjson = nsjsonserialization.datawithjsonobject(submitdata, options: nsjsonwritingoptions.prettyprinted, error: &error) if (error == nil) { let submitjsonstring = nsstring(data: cafejson, encoding: nsutf8stringencoding) var url = nsurl(string: "http://localhost:3000/people.json") var request = nsmutableurlrequest(url: url!) var requestdata = submitjsonstring?.datausingencoding(nsutf8stringencoding) request.httpbody = requestdata request.httpmethod = "post" request.setvalue("application/json", forhttpheaderfield: "content-type") request.setvalue("application/json", forhttpheaderfield: "accept") request.timeoutinterval = 10 } } func connection(connection: nsurlconnection, didreceiveresponse response: nsurlresponse) { var response = response nshttpurlresponse if (response.statuscode >= 200 && response.statuscode <= 299) { self.navigationcontroller?.popviewcontrolleranimated(true) var alert = uialertview(title: "success", message: "cafe submitted. we'll review in few business days.", delegate: self, cancelbuttontitle: "ok") alert.show() } else { var alert = uialertview(title: "oops..", message: "it seems there kind of server error, please try again later", delegate: self, cancelbuttontitle: "ok") alert.show() } } func connection(connection: nsurlconnection, didfailwitherror error: nserror) { self.dismissviewcontrolleranimated(true, completion: { var alert = uialertview(title: "oops..", message: "it seems there kind of server error, please try again later", delegate: self, cancelbuttontitle: "ok") alert.show() }) } }
in ruby code have tried variety of different paperclip options, seems near broken. tried decode base64 , save myself little no success.
some of things tried:
data = base64.decode64(params[:thumbnail_data]) file.open("test.jpg", "wb") |f| f.write data end data = base64.decode64(params[:thumbnail_data].split(",")[-1]) file.open("test.jpg", "wb") |f| f.write data end
it seems no matter do, whenever try open uploaded image preview says file has been corrupted. problem nsdata endianness? or perhaps i'm not formatting base64 correctly? i've tried using variety of gems well.
you set thumbnail_data base64 code shown below , change request http body:
var submitdata: dictionary<string, anyobject>! submitdata = ["name": "brian"] submitdata["thumbnail_data"] = "r0lgodlhaqabaiaaaaaaap///yh5baeaaaaalaaaaaabaaeaaaibraa7" let session = nsurlsession.sharedsession() let request = nsmutableurlrequest(url: nsurl(string: "http://localhost:3000/people")!) request.setvalue("application/json", forhttpheaderfield: "content-type") request.httpbody = try! nsjsonserialization.datawithjsonobject(submitdata, options: []) request.httpmethod = "post" let task = session.datataskwithrequest(request) { (data: nsdata?, response: nsurlresponse?, error: nserror?) in //handle server response } task.resume()
specially if want upload image directly device, in case should first create representation , encode it:
let jpegrep = uiimagejpegrepresentation(image!, 0.75) let base64image = jpegrep!.base64encodedstringwithoptions([])
where image uiimage object , 0.75 image quality
on server side, if you're using paperclip gem, should have this:
image = stringio.new(base64.decode64(params[:thumbnail_data])) something.create(:image => image)
hope helps
Comments
Post a Comment