gpt4 book ai didi

ios - 将 UIImage 编码为 Base64 字符串在传输到服务器时不起作用

转载 作者:行者123 更新时间:2023-11-30 13:27:11 24 4
gpt4 key购买 nike

将 UIImage 编码为 Base64 字符串可以在设备上工作,但将字符串传输到服务器会以某种方式损坏字符串并阻止服务器成功解码图像。

对这个问题有什么建议吗?

        // Define params
params["thumbnail_base64"] = imageToBase64(blockSet.thumbnailURL)
...

// Convert params -> query string
let postString = buildQueryString(params)

// Define upload URL
let uploadURL = NSURL(string: RootURL + UploadFilePath)!

// Hit server
let request = NSMutableURLRequest(URL: uploadURL)
request.HTTPMethod = "POST"
request.HTTPBody = postString.dataUsingEncoding(NSUTF8StringEncoding)
...

private func buildQueryString(parameters: [String:String], omitQuestionMark: Bool = false) -> String {
var urlVars = [String]()
for (k, var v) in parameters {
v = v.stringByAddingPercentEncodingWithAllowedCharacters(NSCharacterSet.URLQueryAllowedCharacterSet())!
urlVars += [k + "=" + "\(v)"]
}
return ((urlVars.isEmpty || omitQuestionMark) ? "" : "?") + urlVars.joinWithSeparator("&")
}


private func imageToBase64(filename: String) -> String {
// Get image path
let imagePath = getFilePath(filename)

// Convert image to base64 or return empty string
if let imageData = NSData(contentsOfFile: imagePath) {
let base64String = imageData.base64EncodedStringWithOptions(.EncodingEndLineWithLineFeed)
return base64String
} else {
printError("Error converting image to Base64: missing image. Filename: \(filename)")
return ""
}
}

最佳答案

问题在于 queryString,base64 是包含许多字符的长文本,让 JSON 为您完成工作

使用下一个(带有 NodeJS 的一些示例)

  let params = NSMutableDictionary();
//you can only set `serializable` values
params.setValue(imageToBase64(),forKey:"base64")
params.setValue(username,forKey:"username")
params.setValue(["array","of","string"],forKey:"arr")

let uploadURL = NSURL(string: theURL)!

// Hit server
let request = NSMutableURLRequest(URL: uploadURL)
request.HTTPMethod = "POST"

request.setValue("application/json", forHTTPHeaderField: "Content-Type")

do {
let jsonData = try NSJSONSerialization.dataWithJSONObject(params, options: NSJSONWritingOptions(rawValue: 0))
request.HTTPBody = jsonData
let session = NSURLSession.sharedSession()

session.dataTaskWithRequest(request, completionHandler: {data, response, error -> Void in
print("Response: \(response)")
}).resume()


} catch let error as NSError {
print(error)
}

节点:

var buffer = new Buffer(request.body["base64"], 'base64')
fs.writeFile('test.jpeg',buffer,"base64"); //Works
var username = request.body["username"];
var someStringsArr = request.body["arr"]

顺便说一下...

您编写了函数buildQueryString,该函数已存在于Foundation

let urlComponents = NSURLComponents(string: "http://myUrl.com/getApi/")!
urlComponents.queryItems = [NSURLQueryItem]()
urlComponents.queryItems!.append(NSURLQueryItem(name:"myKeyA",value:"myValueA"))
urlComponents.queryItems!.append(NSURLQueryItem(name:"myKeyB",value:"myValueB"))

print(urlComponents.URL!) //http://myUrl.com/getApi/?myKeyA=myValueA&myKeyB=myValueB

如果想通过URL发送GET参数,请使用url查询

关于ios - 将 UIImage 编码为 Base64 字符串在传输到服务器时不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37034221/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com