Swift 4 Alamofire分段上传无法正常工作 [英] Swift 4 Alamofire multipart upload not working
问题描述
我正在使用alamofire 4.7和Swift 4
I am using alamofire 4.7 and swift 4
我需要将图像和json上传到服务器.
I need to upload image and json to server.
我正在使用下面的代码上传bu我遇到了结果失败,但是数据正在服务器中插入但没有得到响应,显示一些序列化错误,就像这样
I am using the following code below for uploading bu I am getting result failure but data is inserting in server but not getting response, showing some serialization error as something like this
▿ result : FAILURE: responseSerializationFailed(Alamofire.AFError.ResponseSerializationFailureReason.jsonSerializationFailed(Error Domain=NSCocoaErrorDomain Code=3840 "Invalid value around character 0." UserInfo={NSDebugDescription=Invalid value around character 0.}))
▿ failure : AFError
▿ responseSerializationFailed : ResponseSerializationFailureReason
▿ timeline : Timeline: { "Request Start Time": 548835779.066, "Initial Response Time": 548835779.074, "Request Completed Time": 548835779.127, "Serialization Completed Time": 548835779.127, "Latency": 0.008 secs, "Request Duration": 0.061 secs, "Serialization Duration": 0.000 secs, "Total Duration": 0.061 secs }
- requestStartTime : 548835779.06617701
- initialResponseTime : 548835779.07390201
- requestCompletedTime : 548835779.12704694
- serializationCompletedTime : 548835779.12748504
- latency : 0.0077250003814697266
- requestDuration : 0.060869932174682617
- serializationDuration : 0.00043809413909912109
- totalDuration : 0.061308026313781738
▿ _metrics : Optional<AnyObject>
================================================ ==================
=================================================================
let auth : String = MitraModal.sharedInstance().getBasicAuthenticationString()
let headers = ["Authorization": auth, "Content-type": "multipart/form-data"]
Alamofire.upload(multipartFormData: { (multipartFormData) in
multipartFormData.append("\(parameters)".data(using: String.Encoding.utf8)!, withName: "data" as String)
if (!imageArray.isEmpty) {
for item in imageArray {
multipartFormData.append(item!, withName: "file", fileName: "image.png", mimeType: "image/png")
}
}
}, usingThreshold: UInt64.init(), to: url, method: .post, headers: headers) { (result) in
switch result{
case .success(let upload, _, _):
upload.responseJSON { response in
if let JSON = response.result.value
{
print("JSON: \(JSON)")
onCompletion?(JSON as? JSON)
print("Successfully uploaded")
}
if let err = response.error {
onError?(err)
return
}
onCompletion?(nil)
}
case .failure(let error):
print("Error in upload: \(error.localizedDescription)")
onError?(error)
}
}
}
有人帮忙吗?
推荐答案
由于我是新手,但几天前,我在上传图片时遇到了同样的问题,必须使用 file 来接受图片由于您的图片标记在服务器端是"strong>",所以该标签包含 withName:"file" .
As i'm newbie, but Few days ago, i had same problem while uploading image, you must have to accept image by using file on the server side because of your image tag consist withName: "file" .
func AlamofireUploadImages(){
let url : String = URL_IP+"/ZameenServer/api/addNewProperty.php"
for img in HOUSEImages{
let data = UIImageJPEGRepresentation(img, 0.2)!
ImagesData.append(data)
}
let parameters = [
"userId" : "5",
"unit" : "6789"
] //Optional for extra parameter
Alamofire.upload(multipartFormData: { multipartFormData in
for imageData in self.ImagesData {
multipartFormData.append(imageData, withName: "file[]", fileName: self.randomString(length: 5)+".jpeg", mimeType: "image/jpeg")
}
for (key, value) in parameters {
multipartFormData.append((value?.data(using: String.Encoding.utf8)!)!, withName: key)
} //Optional for extra parameters
},
to:url)
{ (result) in
switch result {
case .success(let upload, _, _):
upload.uploadProgress(closure: { (progress) in
print("Upload Progress: \(progress.fractionCompleted)")
})
upload.responseJSON
{
response in
print("Response :\(response.result.value)")
}
case .failure(let encodingError):
print("no Error :\(encodingError)")
}
}
}
注意:由于我正在上传图像数组,因此要上传多张图像,请使用 withName:"file []" ;对于单个图像,请使用 withName: 文件"
NOTE: As i'm uploading array of images so for uploading multile images use withName: "file[]" or for single image use withName: "file"
可能对您有帮助.
谢谢
这篇关于Swift 4 Alamofire分段上传无法正常工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!