【问题标题】:swift upload image to server use image as parameter快速上传图片到服务器使用图片作为参数
【发布时间】:2016-12-08 01:45:04
【问题描述】:

我尝试将图像上传到服务器并使用邮递员对其进行测试。有用。在标题中,我使用授权承载唯一ID。在正文中,我以图像为键设置表单数据。它得到了 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")
                }

【问题讨论】:

  • 你为什么不试试 Alamofire。
  • 因为我更喜欢使用标准的 swift 版本。

标签: asp.net swift swift2 image-uploading postman


【解决方案1】:

尝试使用您的 base64String 和您的“(userID)”和“(uniqueID)”打印()。其他一切看起来都不错,我感觉这些值并没有按预期出现。确保像在 var fname 中那样用引号打印它们,这样您就可以看到服务器实际接收的内容。

【讨论】:

  • 我可以通过打印获得该用户 ID 和唯一 ID。 userID 和 uniqueID 没有错。
【解决方案2】:

只要您使用 Postman 点击“生成代码”按钮并选择 Swift 语言并使用此代码上传您的图片,希望对您有所帮助。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-03-08
    • 1970-01-01
    • 2011-06-01
    相关资源
    最近更新 更多