我一直在与这个争论了很长时间。我试图上传一个图像到服务器,但不断收到500错误。为什么我会在这个http POST请求中收到内部服务器错误(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.]
+0
你还在上传什么后端?你有权访问错误日志吗?你得到什么回应?尝试使用Chrome的邮递员应用程序将请求复制到后端,如果它在那里工作,那么您知道问题出在swift代码上。这里没有足够的信息来提供准确的答案 –
+0
@Scriptable其REST风格的web服务。不,我没有访问错误日志。我得到这个错误:数据从500错误:[“codesc”:GENERALERROR,“code”:5001,“msg”:从字符串“可选(1004007)”转换为类型'双'无效。]我将更新我的问题与这个信息。 –
+0
使用任何其他休息客户端进行api调用时,您会得到正确的结果吗? –