如何使用Swift将图像从iOS上传到Ruby/Rails服务器
问题描述:
我有一个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?我尝试过使用各种宝石。
答
你可以设置你的thumbnail_data只是Base64的代码,如下图所示,改变请求的HTTP体:
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()
特别是如果你想直接从设备上载的图像,在这种情况下,你应该先创建的表示,然后对其进行编码:
let jpegRep = UIImageJPEGRepresentation(image!, 0.75)
let base64Image = jpegRep!.base64EncodedStringWithOptions([])
当图像是UIImage对象和0.75是图像质量
在服务器端,如果你使用回形针宝石,你应该有这样的事情:
image = StringIO.new(Base64.decode64(params[:thumbnail_data]))
Something.create(:image => image)
希望这有助于
答
我有一个类似的问题,后头痛几天来解:
只需更换self.capturePhotoView.image
与图像
if let capturePhotoImage = self.capturePhotoView.image {
if let imageData = UIImagePNGRepresentation(capturePhotoImage) {
let encodedImageData = imageData.base64EncodedString(options: NSData.Base64EncodingOptions(rawValue: 0))
}
}
,然后在你的服务器端假设Ÿ这样对其进行解码你在你的图像模型上有回形针。
image = StringIO.new(Base64.decode64(params[:image].tr(' ', '+')))
image.class.class_eval { attr_accessor :original_filename, :content_type }
image.original_filename = SecureRandom.hex + '.png'
image.content_type = 'image/png'
create_image = Image.new(image: image)
create_image.save!
希望这有助于https://blog.kodius.io/2016/12/30/upload-image-from-swift-3-ios-app-to-rails-5-server/
请点击这里查看我的回答:http://stackoverflow.com/questions/27234065/how-to-upload-a-base-64-image-to-rails-回形针/ 28036282#28036282 – Jared 2015-01-20 01:25:25