2017-02-14 36 views
0

我正在使用Swift 3.0构建一个应用程序用于学习目的。 其中一个功能是从(到)SQL Server数据库表中提取和保存数据。其中一列是将IMAGE(照片)存储在表中:表中的数据类型是Image(system.Byte[]SQL Server如何通过web api在swift中将图像保存到数据库表

我可以通过Web API的照片栏,并显示在图像组件是这样的:

let encodedImageData = My web api url 
let imageData = NSData(base64EncodedString: encodedImageData options: .allZeros) 
let image = UIImage(data: imageData) 
let imageView.image = image 

我有问题,将图像保存到通过网络API数据库(可以节省等栏目,但有问题与图像列)。 我试过这个:

let data = UIImagePNGRepresentation(image) as NSData? 

但失败。

我的web API和如下调用:

func post(parameters : Dictionary<String, String>, urlString : String) { 


    var request = URLRequest(url: URL(string: urlString)!) 
    let session = URLSession.shared 
    request.httpMethod = "POST" 
    request.addValue("application/json", forHTTPHeaderField: "Content-Type") 
    request.addValue("application/json", forHTTPHeaderField: "Accept") 
    request.httpBody = try! JSONSerialization.data(withJSONObject: parameters) 

    let task = session.dataTask(with: request) { data, response, error in 
     guard let data = data, error == nil else { 
      print("error: \(error)") 
      return 
     } 

     do { 
      if let json = try JSONSerialization.jsonObject(with: data) as? [String: Any] { 
       let success = json["success"] as? Int         // Okay, the `json` is here, let's get the value for 'success' out of it 
       print("Success: \(success)") 
      } else { 
       let jsonStr = String(data: data, encoding: .utf8) // No error thrown, but not dictionary 
       print("Error could not parse JSON: \(jsonStr)") 
      } 
     } catch let parseError { 
      print(parseError)               // Log the error thrown by `JSONObjectWithData` 
      let jsonStr = String(data: data, encoding: .utf8) 
      print("Error could not parse JSON: '\(jsonStr)'") 
     } 
    } 

    task.resume() 


} 

@IBAction func insert(){ 

let imageData = UIImagePNGRepresentation(myimageview.image!) as NSData? 

post(parameters: ["Name": nametxt.text!,"Address": addresstxt.text!,"photoname": photonametxt.text!,"photo": String(describing: imageData),"url": urltxt.text! ], urlString: "http://XXXXXXX/api/myfavorites") 

} 

有人可以帮助我在斯威夫特看看图片保存方法,数据库中的表?

+0

请出示您的Web API调用的代码;还告诉我们在哪个(传输)格式的Web服务器期望的图像数据 –

+0

@AndreasOetjen:我已经添加了网页api。在Web服务器SQL Server数据库表中,image(photo)列是IMAGE格式 - Byte []。谢谢! – user7505698

+0

服务器有任何错误返回吗? – Terence

回答

0

我认为你的图片使用了错误的数据结构。而不是使用NSDataString(describing:)(这绝对你想要的东西不一样),你应该直接使用base64编码字符串,如下面的代码:

@IBAction func insert(){ 

    let imageBase64String = UIImagePNGRepresentation(myimageview.image!)?.base64EncodedString() 

    post(parameters: ["Name": nametxt.text!,"Address": addresstxt.text!,"photoname": photonametxt.text!,"photo": imageBase64String,"url": urltxt.text! ], urlString: "http://XXXXXXX/api/myfavorites") 

} 
相关问题