我有一个ruby/rails应用程序,我希望在JSON请求有效内容中以Base64格式接受图像上传。基本的应用程序结构如下:如何使用Swift将图像从iOS上传到Ruby/Rails服务器
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 to submit a dynamic image, but I switched it to a
// hard-coded 1x1 GIF just to get a grip on how to do this on
// the backend before attempting too much 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 as NSHTTPURLResponse
if (response.statusCode >= 200 && response.statusCode <= 299) {
self.navigationController?.popViewControllerAnimated(true)
var alert = UIAlertView(title: "Success", message: "Cafe was successfully submitted. We'll review it in a few business days.", delegate: self, cancelButtonTitle: "Ok")
alert.show()
} else {
var alert = UIAlertView(title: "Oops..", message: "It seems there was some 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 was some kind of server error, please try again later", delegate: self, cancelButtonTitle: "Ok")
alert.show()
})
}
}
在我的Ruby代码我已经尝试了各种不同的回形针的选择,这似乎附近的残破。我也试着解码Base64,并自己保存,几乎没有成功。
一些我试过的东西:
data = Base64.decode64(params[:thumbnail_data])
File.open("test.jpg", "wb") do |f| f.write data end
data = Base64.decode64(params[:thumbnail_data].split(",")[-1])
File.open("test.jpg", "wb") do |f| f.write data end
好像不管我做什么,每当我试图打开上传的图片预览说,该文件已损坏。这个问题可能与NSData的排序有关吗?或者我没有正确格式化Base64?我尝试过使用各种宝石。
请点击这里查看我的回答:http://stackoverflow.com/questions/27234065/how-to-upload-a-base-64-image-to-rails-回形针/ 28036282#28036282 – Jared 2015-01-20 01:25:25