私はサーバーにイメージをアップロードして、郵便番号を使用してテストしようとします。できます。ヘッダーでは、認証bearerのuniqueIDを使用します。本文では、イメージをキーとしてフォームデータを設定します。それは以下の添付ファイルとして200の応答を得ました。 イメージをサーバーにアップロードするパラメータとしてイメージを使用
しかし、私はこのように使用し迅速にしようとすると、それが応答として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が起こるチェック設定されていないか空のキーです。以下のスクリーンショットのようになります。
私のスウィフトコードを修正する方法イメージをサーバーに正しくアップロードできます(レスポンス200を得る)?
更新:
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