1

我已经为此奋斗了很多年。我正在尝试将图像上传到服务器,但不断收到 500 错误。

这是我用来获取图像的代码,对其进行base64编码,然后将其添加到字典中。

 if let imageDataToUpload = UIImageJPEGRepresentation(selectedImage, 1.0) {


            let encodedImageData = imageDataToUpload.base64EncodedString(options: [])

            let extras = "data:image/jpeg;base64,"

            let postBody = [
                "image": extras + encodedImageData,
                "id": id,
                "instruction": "1",
                "ext": ""
            ]

            let endPoint = UrlFor.uploadPhoto

            ApiManager().apiPostImage(endPoint: endPoint, postBody: postBody, callBackFunc: handleResultOfUploadPhoto) }

这是我用来执行实际 POST 请求的代码。您会注意到我正在尝试将帖子正文转换为 JSON 对象。

func apiPostImage(endPoint: String, postBody: [String: Any]?, callBackFunc: @escaping (ResultOfApiCall) -> Void) {

    // get the sessionKey
    guard let sessionKey = KeyChainManager().getSessionKey() else {
        print("error getting session key")
        AppDelegate().signUserOut()
        return
    }

    // create a url with above end point and check its a valid URL
    guard let url = URL(string: endPoint) else {
        print("Error: cannot create URL")
        return
    }

    // set up the request
    var urlRequest = URLRequest(url: url)
    urlRequest.httpMethod = "POST"

    if let postBody = postBody {
        do {
            try urlRequest.httpBody = JSONSerialization.data(withJSONObject: postBody, options: [])
        } catch {
            print("problems creating json body")
        }
    }

    // set up the header
    let config = URLSessionConfiguration.default
    config.httpAdditionalHeaders = [
        "Accept": "application/json",
        "apiKey": "0101010-0101010", // not the real apiKey
        "usrKey": sessionKey,
        "appInfo" : "appcode:1000|version:2.0.37",
        "Content-Type": "application/json"
    ]

    let session = URLSession(configuration: config)

    let task = session.dataTask(with: urlRequest, completionHandler:
        { (data: Data?, response: URLResponse?, error: Error?) -> Void in

            let (noProblem, ResultOfCall) = self.checkIfProblemsWith(data: data, response: response, error: error)

            guard noProblem else {
                callBackFunc(ResultOfCall)
                return
            }

            let serializedData: [String:Any]
            do {

                // safe bc checked for nil already.
                serializedData = try JSONSerialization.jsonObject(with: data!, options: []) as! [String:Any]

            } catch  {

                callBackFunc(ResultOfApiCall.errorWhileSerializingJSON)
                return
            }

            // pass serialized data back using the callBackFunc
            callBackFunc(ResultOfApiCall.success(serializedData))
    })

    task.resume()
}

API 是 RESTful 的。我无权访问 API 错误日志,但我从 API 收到了这个错误:

["codesc": GENERALERROR, "code": 5001, "msg": Conversion from string "Optional(1004007)" to type 'Double' is not valid.]
4

3 回答 3

0

好的,我想通了。感谢@Scriptable 推动我深入挖掘返回的错误消息。

似乎 API 期望其中一个属性是双精度的,即 id 属性,但我传入的是一个字符串。

我还必须将 postBody Dictionary 从可选更改为非可选。

改变了这一点,它解决了这个问题。

于 2017-02-16T10:30:49.790 回答
0

500 Internal Server Error 是服务器端错误,这意味着问题可能不在于您的计算机或 Internet 连接,而是网站服务器的问题。

于 2017-02-16T10:07:24.243 回答
0
var  task = URLSession().uploadTask(with: urlRequest, from: imageData) { (data , response , error) in
        // Check Response here
    })

task.resume()

您发送的数据是可选值,请确保您传递的数据不是可选值。

于 2017-02-16T10:33:11.887 回答