asp.net - 快速上传图像到服务器使用图像作为参数

标签 asp.net swift swift2 image-uploading postman

我尝试将图片上传到服务器并使用 postman 对其进行测试。有用。在 header 中,我使用授权承载 uniqueID。在正文中,我将以图像为键的表单数据设置为。它得到了 200 作为响应作为下面的附件。 enter image description here

但是当我尝试像这样使用 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")
                }

最佳答案

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

关于asp.net - 快速上传图像到服务器使用图像作为参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41030446/

相关文章:

asp.net - 如何从 aspx 页面引用母版页?

c# - 正则表达式特定日期格式

json - 单元测试在 Swift 中使用 REST 调用的方法

swift - 无法将类型 'NSMutableArray' 的值转换为预期的参数类型 '[SKAction]'

swift - 为什么我们需要指定init方法?

c# - 如何在 C# 上更新和显示数据库结果

asp.net - 返回 404 错误的脚本文件

ios - 如何以编程方式将图像设置为在每个设备上具有相同的相对大小和位置?

ios - 关闭 UITableViewController 时保留选定的行 - Swift,UITableView

swift - 下标 swift 2.2 的模糊使用