问题描述
我的php代码在服务器上创建一个空图像
my php code creates an empty image on server
这是我的代码(swift4):
here is my code (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
中不允许这些字符串,除非您对它们进行百分比编码。另外,我们不知道消息
内有哪些字符。
The fundamental issue is that your x-www-form-urlencoded
request is not well-formed. You have explicitly requested it to create base64 string with newline characters in it, but those are not allowed in x-www-form-urlencoded
unless you percent encode them. Plus, we don't know what sort of characters are inside message
.
我建议:
- 除非你真的需要,否则不要求将换行符添加到base64字符串中;但
- 百分比转义字符串值,无论如何,因为我不知道您对
消息
有什么样的值。
- Not request newline characters to be added to the base64 string unless you really needed them; but
- Percent escape the string values, anyway, as I don't know what sort of values you have for
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
}()
}
或者,您可以考虑使用这让你摆脱了创造格式良好的 x-www-form-urlencoded
请求的杂草。
Alternatively, you could consider using Alamofire which gets you out of the weeds of creating well-formed x-www-form-urlencoded
requests.
这篇关于在swift 4中使用Base64的Image to String的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!