Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/ruby-on-rails/59.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何使用Swift将图像从iOS上传到Ruby/Rails服务器_Ios_Ruby On Rails_Ruby_Swift - Fatal编程技术网

如何使用Swift将图像从iOS上传到Ruby/Rails服务器

如何使用Swift将图像从iOS上传到Ruby/Rails服务器,ios,ruby-on-rails,ruby,swift,Ios,Ruby On Rails,Ruby,Swift,我有一个ruby/rails应用程序,我想在JSON请求负载中接受Base64格式的图像上传。应用程序的基本结构如下所示: import UIKit import MapKit class NewCafeDetailsTableViewController: UITableViewController, NSURLConnectionDataDelegate { @IBOutlet weak var submitButton: UIButton! @IBOutlet weak

我有一个ruby/rails应用程序,我想在JSON请求负载中接受Base64格式的图像上传。应用程序的基本结构如下所示:

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()

        })
    }

}

似乎无论我做什么,每当我试图打开上传的图像预览时,都会说文件已损坏。问题是否与NSData的持久性有关?或者我没有正确格式化Base64?我也尝试过使用各种gem。

您可以将缩略图数据设置为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()
其中图像是UIImage对象,0.75是图像质量

在服务器端,如果您使用的是回形针gem,您应该有如下内容:

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!
希望这有帮助

请在此处查看我的答案:
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!