使用 AFNetworking 将图像保存在服务器上不起作用
Posted
技术标签:
【中文标题】使用 AFNetworking 将图像保存在服务器上不起作用【英文标题】:Saving image on server using AFNetworking not working 【发布时间】:2018-03-16 15:17:47 【问题描述】:我需要在我的服务器上保存图像我尝试了以下方法:
func saveImageOnServer(_ image: UIImage)
let fileid:String = files id here
let parameters : NSMutableDictionary? = [
"fileId": fileid]
let filename:String = filename here
let url = url here
let afHTTP : AFHTTPRequestSerializer = AFHTTPRequestSerializer()
let request: NSMutableURLRequest = afHTTP.multipartFormRequest(withMethod: "POST", urlString: url, parameters: parameters as? [String : Any], constructingBodyWith: (formData: AFMultipartFormData) in
let imageData = UIImageJPEGRepresentation(image as UIImage, 0.5)!
formData.appendPart(withFileData: imageData, name: "uploaded_file", fileName: filename, mimeType: "image/*")
, error: nil)
let manager = AFURLSessionManager()
let uploadTask:URLSessionUploadTask = manager.uploadTask(withStreamedRequest: request as URLRequest, progress: nil, completionHandler: (response, responseObject, error) in
print(responseObject as Any)
)
uploadTask.resume()
但由于某种原因,无论我在 php 代码中进行什么更改,即使我有如下简单的东西,responseObject 总是返回 nil:
public function uploadColoringImage ()
return "1";
任何帮助将不胜感激!
【问题讨论】:
你为什么不用Alamofire 而不是AFNetworking? 我在整个应用程序中都使用过它,它工作得很好,但我以前从未上传过图片:) 仍然无法解决问题! 检查this answer,他们使用AFHTTPRequestOperationManager
,它可能有用(是的,这是在Objective-C中,但它可以帮助你了解你做错了什么)。
【参考方案1】:
将图片上传到 API 服务器的最简单方法是将其转换为 base64 字符串:
let image: UIImage = UIImage(named:"myImage")!
let imageData: Data = UIImageJPEGRepresentation(image, 1.0)!
let strBase64 = imageData.base64EncodedString(options: .lineLength64Characters)
然后只需将 strBase64 设置为 POST 或 PUT 参数并拍摄请求 然后像这样在后端将 base64 解码为 jpeg:
https://***.com/a/17811089/5765283
【讨论】:
这是 Swift,使用Data
,而不是 NSData
。
我觉得差别不大,这段代码只是伪代码解释。这不是学校,这是 ***。
对。这是 Stack Overflow,其中的答案是有用的,这意味着答案应该是正确的,并使用正确的代码和正确的类。这里发布的问题中有一半是有人复制和粘贴错误代码的结果。无需为该问题做出贡献。 NSData
用于 Objective-C,Data
用于 Swift。所以是的,很大的不同。【参考方案2】:
这对我来说很好,希望它有所帮助:
func createBodyWithParams(parameters: [String : String]?, filePathKey: String?, imageDataKey: NSData, boundary: String) -> NSData
let body = NSMutableData();
if parameters != nil
for (key, value) in parameters!
body.append("--\(boundary)\r\n".data(using: String.Encoding.utf8)!)
body.append("Content-Disposition: form-data; name=\"\(key)\"\r\n\r\n".data(using: String.Encoding.utf8)!)
body.append("\(value)\r\n".data(using: String.Encoding.utf8)!)
let filename = filename here
let mimetype = "image/*"
body.append("--\(boundary)\r\n".data(using: String.Encoding.utf8)!)
body.append("Content-Disposition: form-data; name=\"\(filePathKey!)\"; filename=\"\(filename)\"\r\n".data(using: String.Encoding.utf8)!)
body.append("Content-Type: \(mimetype)\r\n\r\n".data(using: String.Encoding.utf8)!)
body.append(imageDataKey as Data)
body.append("\r\n".data(using: String.Encoding.utf8)!)
body.append("--\(boundary)--\r\n".data(using: String.Encoding.utf8)!)
return body
// upload image to server
func saveImageOnServer(_ image: UIImage)
let fileid:String = "\(jsonData["categories"][selectedCategoryIndex]["images"][selectedImageIndex]["fileid"].stringValue)"
print(jsonData)
let param : NSMutableDictionary? = [
"fileId": fileid]
let address = URL(string: "URL here")!
var request = URLRequest(url: address)
request.httpMethod = "POST"
let boundary = "Boundary-\(NSUUID().uuidString)"
request.setValue("multipart/form-data; boundary=\(boundary)", forHTTPHeaderField: "Content-Type")
let imageData = UIImagePNGRepresentation(image)
if imageData == nil
return
request.httpBody = createBodyWithParams(parameters: (param as! [String : String]), filePathKey: "uploaded_file", imageDataKey: imageData! as NSData, boundary: boundary) as Data
// launch session
let task = URLSession.shared.dataTask(with: request, completionHandler: (data, response, error) in
// get main queue to communicate back to user
DispatchQueue.main.async
print(response)
if error == nil
do
let json = try JSONSerialization.jsonObject(with: data!, options: JSONSerialization.ReadingOptions.mutableContainers) as? NSDictionary
print(json)
guard let parseJSON = json else
print("error while parsing")
return
print(parseJSON)
catch
print("Caught an error: \(error)")
else
print(error)
)
task.resume()
【讨论】:
以上是关于使用 AFNetworking 将图像保存在服务器上不起作用的主要内容,如果未能解决你的问题,请参考以下文章