从应用程序Swift上传图像文件

时间:2017-10-21 01:41:50

标签: ios swift image file-upload

我正在尝试将图片文件上传到我的服务器。屏幕下方显示邮递员的电话。

KEY: “image”价值: 123.png [image file] 形式 - 数据正文。

enter image description here

我想在我的应用程序中使用swift实现相同的功能。我尝试了不同的解决方案,但dint找到了合适的解决方案。

我是在UIImagePicker的帮助下选择图像的:

func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) 
            {
                let image = info[UIImagePickerControllerOriginalImage] as? UIImage
                self.dismiss(animated: true, completion: nil)
                uploadImage(image: image!, url: "profile_image/")
            }

我调用uploadImage函数来上传图片。

func uploadImage(image: UIImage, url: String) {
        let urlString = "http://example.com/path/"+url
        guard let url = URL(string: urlString) else { return }
        let request = NSMutableURLRequest(url: url)
        request.httpMethod = "POST"
        let token = UserDefaults.standard.object(forKey: "token") as? String
        request.addValue("Token "+token!, forHTTPHeaderField: "Authorization")
        let imageData = UIImagePNGRepresentation(image)!.base64EncodedData()
        //let postString = "image=\(imageData))"
        //request.httpBody = postString.data(using: .utf8)

    let imgDict = ["image": imageData]

    do {
        let jsonBody = try JSONEncoder().encode(imgDict)
        print(jsonBody)
        request.httpBody = jsonBody
    } catch let jsonError {
        print(" Parsing Error: "+jsonError.localizedDescription)
    }

        URLSession.shared.dataTask(with: request as URLRequest) { (data, response, error) in
            if error != nil {
                print("Image upload API Error: "+error!.localizedDescription)
            }
            guard let data = data else { return }
            do {
                print(data)
                let responseData = try JSONDecoder().decode(BasicResponseParameter.self, from: data)
                print(responseData)

                if responseData.success {
                    print("Image uploaded")
                }
                else {
                    print("Image upload API Failed : "+responseData.message!)
                    DispatchQueue.main.async(execute: {
                        popAlert(title: "FAILED", message: responseData.message!, owner:self)
                    })
                }
            } catch let jsonError {
                print("Image upload API JSON Error :"+jsonError.localizedDescription)
            }
            }.resume()
    }

任何帮助表示感谢。

1 个答案:

答案 0 :(得分:0)

我建议您进行编码(将图像发送到服务器时)和解码(查询图像时)将图像转换为base64格式

  

编码

let img = /// this is your image 
let encodedString =   UIImagePNGRepresentation(img)?.base64EncodedString() 
  

解码:

let data_from_response = /// from your response 
let decodeData = Data(base64Encoded: data_from)

由于您在请求正文中发送了dictionary,因此您需要将dictionary转换为json

guard let imgDataString = String.init(data: encodedString, encoding: String.Encoding.utf8) else { return } 

let imgDict = ["image": imgDataString ] 

let jsonData = try! JSONSerialization.data(withJSONObject: imgDict, options: .prettyPrinted)

request.httpBody = jsonData 

旁注避免使用implicit optional unwrapping表示!,使用if letguard语句