上传Multipart swift Image Upload内部服务器错误500作为响应

Posted

技术标签:

【中文标题】上传Multipart swift Image Upload内部服务器错误500作为响应【英文标题】:Upload Multipart swift Image Upload internal server error 500 in response 【发布时间】:2017-01-11 13:28:33 【问题描述】:

我迁移到了 swift 3,为此我必须将 Alamofire 升级到 4, 使用多部分请求上传图像在 swift 2 中工作正常,并且具有相同参数的相同 API 成功获得内部服务器错误 500 这是运行良好的 swift 2.3 代码

        Alamofire.upload(
        .POST,
        AppConstants.kAPIBaseURL  + AppConstants.KAPIWidgetUrl + AppConstants.KAPIUpdateUserPhoto,headers: headers,
        multipartFormData:  multipartFormData in
            multipartFormData.appendBodyPart(data: imageData!, name: "image[image]", fileName: "myImage.png", mimeType: "image/png")
            multipartFormData.appendBodyPart(data: "\((UserManager._currentUser?.userID)!)".dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)!, name :"id")
            multipartFormData.appendBodyPart(data: "profile_picture".dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)!, name :"upload_to")


        ,
        encodingCompletion:  encodingResult in
            switch encodingResult 
            case .Success(let upload, _, _):

                upload.responseJSON  (JSON) in
                    let abc   = JSON.result.value as! NSDictionary
                    print(abc)
                    let arrayOfResult = abc["results"] as! NSDictionary
                    let responseMessage = abc["message"] as! String
                    let currentUser: MOUser?
                    currentUser = MOUser.init(object: arrayOfResult)
                    UserManager.setCurrentUser(currentUser)
                    dispatch_async(dispatch_get_main_queue(),
                        //Show Alert in UI
                        print("image uploaded");
                        [self.showAlertViewWithTitle(AppConstants.kEmptyString, message: "\(responseMessage)", dismissCompletion: 

                        )]
                    )
                

            case .Failure(let encodingError):
                print(encodingError);
            
        
    );

以下是出现错误的 Swift 3 代码

Alamofire.upload(
        multipartFormData:  multipartFormData in

            multipartFormData.append(imageData!, withName: "image[image]", fileName: "myImage.png", mimeType: "image/png")
            multipartFormData.append("\(UserManager._currentUser?.userID)".data(using: .utf8, allowLossyConversion: false)!, withName: "id")
            multipartFormData.append("profile_picture".data(using: .utf8, allowLossyConversion: false)!, withName: "upload_to")


    ,
        to: AppConstants.kAPIBaseURL  + AppConstants.KAPIWidgetUrl + AppConstants.KAPIUpdateUserPhoto ,method: .post, headers: headers,
        encodingCompletion:  encodingResult in
            print(encodingResult)
            switch encodingResult 

            case .success(let upload, _, _):
                upload.responseJSON  response in

                    print("SUCCESS RESPONSE: \(response)")
                    SVProgressHUD.dismiss()
                    if let info = response as? Dictionary<String, AnyObject> 

                        if let links = info["links"] as! Dictionary<String, AnyObject>? 
                            if let imgLink = links["image_link"] as? String 

                                print("LINK: \(imgLink)")

                            
                        

                    

                

                upload.uploadProgress  progress in

                    print(progress.fractionCompleted)
                

                upload.responseString(completionHandler:  (response) in
                    print(response)
                    print(response.data)
                    print(response.debugDescription)
                    print(response.description)
                    print(response.result.description)
                    print(response.response)
                )



            case .failure(let encodingError):
                SVProgressHUD.dismiss()
                print("ERROR RESPONSE: \(encodingError)")

            //switch

    
    );

服务器错误是这样的

SUCCESS: "status":"500","error":"Internal Server Error"
SUCCESS
Optional(<NSHTTPURLResponse: 0x60000123cda0>  URL: https://../api///imageupload   status code: 500, headers 
Connection = "keep-alive";
"Content-Length" = 48;
"Content-Type" = "application/json; charset=utf-8";
Date = "Wed, 11 Jan 2017 13:45:59 GMT";
Server = "WEBrick/1.3.1 (Ruby/2.0.0/2015-12-16)";
Via = "1.1 vegur";
"X-Rack-Cache" = "invalidate, pass";
"X-Request-Id" = "78cc7e5c-9bc1-4802-beac-15f8f7c4400a";
"X-Runtime" = "0.167883";

如果有人可以帮助我。谢谢!

【问题讨论】:

您写的是服务器端出现500错误,但您根本没有显示服务器代码,也没有显示服务器错误的原因。至少显示服务器错误原因可能有助于理解问题。 如果它在服务器端我不知道,因为 swift 2.3 中的相同代码工作正常,而在 swift3.0 上我遇到此错误 "SUCCESS: "status":"500","error ":"内部服务器错误" 你确实写了getting internal server error 500... 是的,我收到这个作为回复@Xvolks 您可能想要使用 Charles Proxy 或一些可以向您显示原始请求的类似应用程序。似乎如果它在 2.3 中运行良好,那么您必须在两个代码库之间传递不同的东西。原始请求将让您确切地看到有什么不同——如果有的话。 【参考方案1】:

这一行有区别:

multipartFormData.append("\(UserManager._currentUser?.userID)".data(using: .utf8, allowLossyConversion: false)!, withName: "id")`. 

您不会像在 2.3 版本中那样强制解开 UserManager._currentUser?.userID

multipartFormData.appendBodyPart(data: "\((UserManager._currentUser?.userID)!)".dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)!, name :"id")

因此,您的“id”字段的字符串可能类似于“Optional("userID")”,而不仅仅是您期望的用户 ID。

【讨论】:

非常感谢。正是这个问题

以上是关于上传Multipart swift Image Upload内部服务器错误500作为响应的主要内容,如果未能解决你的问题,请参考以下文章

带有参数和标题的 Alamofire Multipart-form 图像上传 - Swift

Ion Android发送multipart / form-data

Swift 4:如何使用 Alamofire 在参数中发布文件?

Android 使用okhtth上传图片multipart/form-data

React-native node.js 显示错误:多部分:使用 react-native-image-picker 上传图像时未找到边界

请求中上传图片