I'm using this code (Swift) to upload an image that user selected from their photos to a server:
let imageFormatted = UIImageJPEGRepresentation(imageView.image!, 0.5);
let uuid = NSUUID().UUIDString
print ("MARK -- UUID is " + uuid)
Alamofire.upload(
.POST,
"http://www.memer.onlie/upload.php",
multipartFormData: { multipartFormData in
multipartFormData.appendBodyPart(data: imageFormatted!, name: "imagefile",
fileName: uuid + ".jpg", mimeType: "image/jpeg")
},
encodingCompletion: { encodingResult in
switch encodingResult {
case .Success(let upload, _, _):
upload.validate()
upload.responseJSON { response in
dispatch_async(dispatch_get_main_queue()) {
self.displayAlert("Uploaded!", message: "Your meme was uploaded, and you might see it in the app soon!", responseButtonText: "<3")
}
var json = JSON(data: response.data!)
print ("MARK -- JSON response: " + json["response"].stringValue)
}
print ("MARK -- Upload success!")
case .Failure(let encodingError):
print(encodingError)
print ("MARK -- Upload failure!")
self.displayAlert("Issue uploading.", message: "There was an issue uploading your meme.", responseButtonText: "Aww :(")
}
}
)
No image is being uploaded to the server. What can I correct to get this to work?
Edited code.
This thread helps you understand what you have not considered and what you need to do to solve the issue. I guess you need to set request header and body part properly. If you use Alamofire and have to use 'multipart/form-data' encoding type, you can write code like this.
Alamofire.upload(.POST, destURL, headers: yourHeader, multipartFormData: { multipartFormData in
if let imageData = UIImageJPEGRepresentation(image, 0.5) {
multipartFormData.appendBodyPart(data: imageData, name:"file", fileName: "imagefile", mimeType: "image/jpg")
}
// Append parameters you should send
for (key, value) in parameters {
multipartFormData.appendBodyPart(data: value.dataUsingEncoding(NSUTF8StringEncoding)!, name: key)
}
}, encodingCompletion: { encodingResult in
switch encodingResult {
case .Success(let upload, _, _):
upload.validate()
upload.responseJSON { response in
// do something if response is success
}
case .Failure(_):
// do something if response is fail
}
})
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.