我尝试上传图像到服务器并测试它使用邮递员。有用。在标题中,我使用授权承载者uniqueID。在身体中,我设置了形象数据与图像作为关键。作为回应,下面有200个答案。 swift上传图像到服务器使用图像作为参数
但是当我尝试这样使用SWIFT,它得到500作为响应:
let url = NSURL(string: Constant.TestUpload())
let boundary = generateBoundaryString()
let request = NSMutableURLRequest(URL: url!)
request.HTTPMethod = "POST"
request.setValue("multipart/form-data; boundary=\(boundary)", forHTTPHeaderField: "Content-Type")
request.setValue("application/json", forHTTPHeaderField: "Accept")
request.setValue("bearer \(uniqueID)", forHTTPHeaderField: "Authorization")
if (photouser.image == nil){
return
}else{
let image_data = UIImagePNGRepresentation(photouser.image!)
if(image_data == nil){
return
}else{
let body = NSMutableData()
let fname = "\(userID).png"
let mimetype = "image/png"
body.appendData("--\(boundary)\r\n".dataUsingEncoding(NSUTF8StringEncoding)!)
body.appendData("Content-Disposition:form-data; name=\"image\"; filename=\"\(fname)\"\r\n".dataUsingEncoding(NSUTF8StringEncoding)!)
body.appendData("Content-Type: \(mimetype)\r\n\r\n".dataUsingEncoding(NSUTF8StringEncoding)!)
body.appendData(image_data!)
body.appendData("\r\n".dataUsingEncoding(NSUTF8StringEncoding)!)
body.appendData("--\(boundary)--\r\n".dataUsingEncoding(NSUTF8StringEncoding)!)
request.HTTPBody = body
let session = NSURLSession.sharedSession()
let task = session.dataTaskWithRequest(request) {
(data, response, error) -> Void in
if let unwrappedData = data {
do {
print("response:\(response!)")
if let response = response as? NSHTTPURLResponse {
if response.statusCode == 200 {
let json:AnyObject! = try NSJSONSerialization.JSONObjectWithData(unwrappedData, options: NSJSONReadingOptions.AllowFragments) as! AnyObject
print("json:\(json)")
let jsonuser = self.convertStringToDictionary("\(json)")
print("jsonuser:\(jsonuser)")
let imageFile:String = jsonuser!["imageFile"] as! String
dispatch_async(dispatch_get_main_queue()) {
self.photouser.layer.borderWidth = 1
self.photouser.layer.masksToBounds = false
self.photouser.layer.borderColor = UIColor.blackColor().CGColor
self.photouser.layer.cornerRadius = self.photouser.frame.height/2
self.photouser.clipsToBounds = true
self.photouser.image = UIImage(data: NSData(contentsOfURL: NSURL(string:"http://10.8.8.249/profile/\(imageFile)")!)!)
let alertView:UIAlertView = UIAlertView()
alertView.title = "Profile photo updated!"
alertView.message = "Success update profile photo"
alertView.delegate = self
alertView.addButtonWithTitle("OK")
alertView.show()
}
}else if response.statusCode == 500 {
dispatch_async(dispatch_get_main_queue()) {
let alertView:UIAlertView = UIAlertView()
alertView.title = "Failed to upload image!"
alertView.message = "Server error"
alertView.delegate = self
alertView.addButtonWithTitle("OK")
alertView.show()
}
}
}
} catch {
print("Failed to update profile photo: \(error)")
}
}
}
task.resume()
}
}
这是响应日志:
{ URL: http://10.8.8.249/users/uploadtest } { status code: 500, headers {
"Content-Length" = 36;
"Content-Type" = "application/json; charset=utf-8";
Date = "Wed, 07 Dec 2016 05:58:45 GMT";
Server = "Microsoft-IIS/7.5";
"X-Powered-By" = "ASP.NET";
} }
我检查响应500时会发生在身体的关键做没有设置或空键如下截图:
如何纠正我的swift代码,所以我可以正确地将图像上传到服务器(获得响应200)?
更新:这个尝试也没有工作(500为响应):
let session = NSURLSession.sharedSession()
let fname = "\(userID).png"
let mimetype = "image/png"
let url = NSURL(string: Constant.TestUpload())
let boundary = generateBoundaryString()
let request = NSMutableURLRequest(URL: url!)
request.HTTPMethod = "POST"
request.setValue("multipart/form-data; boundary=\(boundary)", forHTTPHeaderField: "Content-Type")
request.setValue("application/json", forHTTPHeaderField: "Accept")
request.setValue("bearer \(uniqueID)", forHTTPHeaderField: "Authorization")
var base64String = image_data!.base64EncodedStringWithOptions(NSDataBase64EncodingOptions(rawValue: 0))
let params:[String: AnyObject] = ["image":[ "content_type": "\(mimetype)", "filename":"\(fname)", "file_data": base64String]]
do{
request.HTTPBody = try NSJSONSerialization.dataWithJSONObject(params, options: NSJSONWritingOptions())
let task = session.dataTaskWithRequest(request, completionHandler: {(data, response, error) in
if let unwrappedData = data {
do{
print("response:\(response!)")
if let response = response as? NSHTTPURLResponse {
if response.statusCode == 200 {
let json:AnyObject! = try NSJSONSerialization.JSONObjectWithData(unwrappedData, options: NSJSONReadingOptions.AllowFragments) as! AnyObject
print("json:\(json)")
let jsonuser = self.convertStringToDictionary("\(json)")
print("jsonuser:\(jsonuser)")
let imageFile:String = jsonuser!["imageFile"] as! String
dispatch_async(dispatch_get_main_queue()) {
self.photouser.layer.borderWidth = 1
self.photouser.layer.masksToBounds = false
self.photouser.layer.borderColor = UIColor.blackColor().CGColor
self.photouser.layer.cornerRadius = self.photouser.frame.height/2
self.photouser.clipsToBounds = true
self.photouser.image = UIImage(data: NSData(contentsOfURL: NSURL(string:"http://10.8.8.249/profile/\(imageFile)")!)!)
let alertView:UIAlertView = UIAlertView()
alertView.title = "Profile photo updated!"
alertView.message = "Success update profile photo"
alertView.delegate = self
alertView.addButtonWithTitle("OK")
alertView.show()
}
}else if response.statusCode == 500 {
dispatch_async(dispatch_get_main_queue()) {
let alertView:UIAlertView = UIAlertView()
alertView.title = "Failed to upload image!"
alertView.message = "Server error"
alertView.delegate = self
alertView.addButtonWithTitle("OK")
alertView.show()
}
}
}
}catch{
print("Failed to update profile photo: \(error)")
}
}
})
task.resume()
}catch{
print ("Oops something wrong")
}
你为什么不试试Alamofire。 –
,因为我更喜欢使用standart swift版本。 – Sarimin