在swift 4中使用Base64的Image to String

时间:2018-03-24 17:34:22

标签: swift image base64

我的php代码在服务器上创建一个空图像

这是我的代码(swift4):

var encoded_img = imageTobase64(image: image1.image!)

func convertImageToBase64(image: UIImage) -> String {
    let imageData = UIImagePNGRepresentation(image)!
    return imageData.base64EncodedString(options:   Data.Base64EncodingOptions.lineLength64Characters)
}

php代码:

$decodimg = base64_decode(_POST["encoded_img"]);
file_put_contents("images/".$imgname,$decodimg);  

准备请求的代码:

@IBAction func BtnSend(_ sender: UIButton) {
    var url = "http://xxxxxx/msg.php"
    var encoded_img = imageTobase64(image: image1.image!)    
    let postData = NSMutableData(data: ("message=" + message).data(using: String.Encoding.utf8)!)
    postData.append(("&encoded_img=" + encoded_img).data(using: String.Encoding.utf8)!)    
     request = NSMutableURLRequest(url: NSURL(string: url)! as URL,
 cachePolicy: .useProtocolCachePolicy,
 timeoutInterval: 20.0)
request.httpMethod = "POST"
request.httpBody = postData as Data

let session = URLSession.shared

let dataTask = session.dataTask(with: 
request as URLRequest, completionHandler:

{ (data, response, error)-> Void in
     ...
})

dataTask.resume()

1 个答案:

答案 0 :(得分:2)

根本问题是您的x-www-form-urlencoded请求格式不正确。您已明确要求它创建带有换行符的base64字符串,但x-www-form-urlencoded中不允许这些字符串,除非您对它们进行百分比编码。另外,我们不知道message内有哪些字符。

我建议:

  • 除非您真的需要,否则不要求将换行符添加到base64字符串中;但
  • 百分比转义字符串值,无论如何,因为我不知道你对message有什么样的价值。

因此:

let parameters = [
    "message": message,
    "encoded_img": convertToBase64(image: image1.image!)
]

let session = URLSession.shared

let url = URL(string: "http://xxxxxx/msg.php")!
var request = URLRequest(url: url, timeoutInterval: 20.0)
request.httpMethod = "POST"
request.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")  // not necessary, but best practice
request.setValue("application/json", forHTTPHeaderField: "Accept")                         // again, not necessary, but best practice; set this to whatever format you're expecting the response to be

request.httpBody = parameters.map { key, value in
    let keyString = key.addingPercentEncoding(withAllowedCharacters: .urlQueryValueAllowed)!
    let valueString = value.addingPercentEncoding(withAllowedCharacters: .urlQueryValueAllowed)!
    return keyString + "=" + valueString
    }.joined(separator: "&").data(using: .utf8)


let dataTask = session.dataTask(with:request) { data, response, error  in
    guard error == nil,
        let data = data,
        let httpResponse = response as? HTTPURLResponse,
        (200 ..< 300) ~= httpResponse.statusCode else {
            print(error ?? "Unknown error", response ?? "Unknown response")
            return
    }

    // process `data` here
}

dataTask.resume()

,其中

func convertToBase64(image: UIImage) -> String {
    return UIImagePNGRepresentation(image)!
        .base64EncodedString()
}

extension CharacterSet {

    /// Character set containing characters allowed in query value as outlined in RFC 3986.
    ///
    /// RFC 3986 states that the following characters are "reserved" characters.
    ///
    /// - General Delimiters: ":", "#", "[", "]", "@", "?", "/"
    /// - Sub-Delimiters: "!", "$", "&", "'", "(", ")", "*", "+", ",", ";", "="
    ///
    /// In RFC 3986 - Section 3.4, it states that the "?" and "/" characters should not be escaped to allow
    /// query strings to include a URL. Therefore, all "reserved" characters with the exception of "?" and "/"
    /// should be percent-escaped in the query string.
    ///
    /// - parameter string: The string to be percent-escaped.
    ///
    /// - returns: The percent-escaped string.

    static var urlQueryValueAllowed: CharacterSet = {
        let generalDelimitersToEncode = ":#[]@" // does not include "?" or "/" due to RFC 3986 - Section 3.4
        let subDelimitersToEncode = "!$&'()*+,;="

        var allowed = CharacterSet.urlQueryAllowed
        allowed.remove(charactersIn: generalDelimitersToEncode + subDelimitersToEncode)

        return allowed
    }()

}

或者,您可以考虑使用Alamofire来帮助您摆脱创建格式正确的x-www-form-urlencoded请求的杂草。