我尝试将图片上传到服务器并使用邮递员进行测试。有用。在标题中,我使用授权承载uniqueID。在身体我设置形式数据与图像作为关键。它得到200作为附件下面的附件。
但是当我尝试使用像这样的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")
}
答案 0 :(得分:0)
尝试使用base64String和“(userID)”& “(唯一身份)”。其他一切看起来都是正确的,我感觉这些价值并没有像预期的那样出现。确保用var fname中的引号打印它们,这样你就可以看到服务器实际接收的内容了。
答案 1 :(得分:0)
只要你使用邮递员点击“生成代码”按钮并选择Swift语言并使用此代码上传你的图片,希望对你有帮助。