2016-12-08 75 views
1

我嘗試上傳圖像到服務器並測試它使用郵遞員。有用。在標題中,我使用授權承載者uniqueID。在身體中,我設置了形象數據與圖像作爲關鍵。作爲迴應,下面有200個答案。 enter image description hereswift上傳圖像到服務器使用圖像作爲參數

但是當我嘗試這樣使用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時會發生在身體的關鍵做沒有設置或空鍵如下截圖: enter image description here

如何糾正我的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

你爲什麼不試試Alamofire。 –

+0

,因爲我更喜歡使用standart swift版本。 – Sarimin

回答

0

嘗試打印()與base64String和你 「(用戶ID)」 & 「(UNIQUEID)」。其他一切都看起來不錯,我有一種感覺,這些價值觀並不像預期的那樣出現。確保像在var fname中那樣用引號將它們打印出來,這樣就可以看到服務器實際上正在接收的內容。

+0

我可以通過打印獲得該用戶ID和唯一ID。用戶ID和唯一ID沒有問題。 – Sarimin

0

只要您使用郵差點擊「生成代碼」按鈕,並選擇Swift語言,並使用此代碼上傳您的圖片,希望有所幫助。