亲爱的stackoverflow社区,
我正在使用Alamofire的iOS应用程序将JSON和图像一起发送到REST API。使用图像选择器检索图像并将其存储在阵列中。问题是,只要我使用来自互联网等的下载图像,图像上传就会起作用。一旦我尝试上传一张照片,这张照片是用我正在使用的手机拍摄的(从照片库中选择)上传失败并抛出400 - 错误请求错误。奇怪的是,当我可以上传照片时,已经从另一部iPhone上拍摄,但是被发送给我,但是用手机本身拍摄的照片都不能正常工作...有人知道为什么会出现这个问题发生?我怀疑,由于HDR和其他东西,iPhone照片的格式或数据可能与下载的不同,但我不确定这是不是问题。
这是我使用的代码,它的标准非常标准:
func POST_WITH_ATACHMENTS(description: String, attachments: [UIImage], returnCompletion: @escaping (Bool) -> ()) {
let parameters = ["ticket":"{ \"description\" : \"" + description + "\"}"]
APIManager.Manager.upload(multipartFormData: { multipartFormData in
for (key, value) in parameters {
multipartFormData.append((value.data(using: .utf8)!), withName: key, mimeType: "application/json")
}
var counter = 1
for image in attachments {
multipartFormData.append(UIImagePNGRepresentation(image)!, withName: "attachments", fileName: "attachment" + String(counter) + ".png", mimeType: "image/png")
counter += 1
}
},
to: restURL!,
method: .post,
headers:["Authorization" : loginString],
encodingCompletion: { encodingResult in
switch encodingResult {
case .success(let upload, _, _):
upload.responseJSON { response in
debugPrint(response)
if (upload.response?.statusCode == 201) {
returnCompletion(true)
} else {
returnCompletion(false)
}
}
case .failure(let encodingError):
print(encodingError)
returnCompletion(false)
}
})
}
答案 0 :(得分:0)
以下是使用AlamoFire上传图片的网络服务
class WebServiceHandler: AnyObject {
func uploadWithAlamofire(Parameters params : [NSObject : AnyObject]?,ImageParameters imgparams : [NSObject : AnyObject]?,Action action : NSString, success: @escaping (AnyObject) -> Void, failure: @escaping (AnyObject) -> Void)
{
var base_url = "YOUR BASE_URL"
base_url.append(action as String)
Alamofire.upload(multipartFormData: { multipartFormData in
if imgparams != nil{
for (key, value) in imgparams! {
if let imageData = UIImageJPEGRepresentation(value as! UIImage, 1) {
multipartFormData.append(imageData, withName: key as! String, fileName: "\(NSDate().timeIntervalSince1970 * 1000)).jpg", mimeType: "image/jpg")
}
}
}
if params != nil
{
for (key, value) in params! {
multipartFormData.append((value as! String).data(using: .utf8)!, withName: key as! String)
}
} }, to: base_url, method: .post, headers: nil,
encodingCompletion: { encodingResult in
switch encodingResult {
case .success(let upload, _, _):
upload.uploadProgress { progress in
print(progress.fractionCompleted)
}
upload.response { [weak self] response in
guard self != nil else {
return
}
let responseString = String(data: response.data!, encoding: String.Encoding.utf8)
return success(responseString as AnyObject)
}
case .failure(let encodingError):
print("error:\(encodingError)")
return failure(encodingError as AnyObject)
}
})
}
func convertToDictionary(text: String) -> [String: Any]? {
if let data = text.data(using: .utf8) {
do {
return try JSONSerialization.jsonObject(with: data, options: []) as? [String: Any]
} catch {
print(error.localizedDescription)
}
}
return nil
}
}
----------------------------USAGE-----------------------------
let dict_params = NSMutableDictionary()
dict_params.set("123", forKey:"YourKey")
dict_params.set("123", forKey:"YourKey")
.
.
.and so on
let imgparam = NSMutableDictionary()
imgparam.set(YourImagetoUpload, forKey: "YourKey")
//here YourImagetoUpload is like imageview.image or UIImage(named: "123.png")
imgparam.set(YourImagetoUpload, forKey: "YourKey")
.
.
.and so on
self.webservice.uploadWithAlamofire(Parameters: dict_params as [NSObject : AnyObject], ImageParameters: imgparam as [NSObject : AnyObject], Action: "API_ACTION_CALL", success: { (success) in
print(success)
}) { (error) in
print(error)
}