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

最佳答案

根本问题是您的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请求的麻烦。

08-03 17:50
查看更多