我正在尝试将图像上传到服务器但却出现500服务器错误。 以下是我的代码:
public func uploadImage(docID: String, image: UIImage, comments: String, onCompletion: @escaping APIPostCallResponse)
{
self.postCallback = onCompletion
let u = "\(IMAGE_UPLOAD)\(docID)&comment=\(comments)"
let urlString: String = u.replacingOccurrences(of: " ", with: "%20")
print(urlString)
guard let url = URL(string: urlString) else
{
return
}
let imageData = UIImageJPEGRepresentation(image, 1)
if imageData != nil
{
let request = NSMutableURLRequest(url: url)
request.httpMethod = "POST"
let loginString = String(format: "%@:%@", getUsername()!, getPassword()!)
let loginData = loginString.data(using: String.Encoding.utf8)!
let base64LoginString = loginData.base64EncodedString()
request.setValue("Basic \(base64LoginString)", forHTTPHeaderField: "Authorization")
let fieldName = "FieldName"
let uniqueId = ProcessInfo.processInfo.globallyUniqueString
let boundary = "------iOS\(uniqueId)"
request.addValue("multipart/form-data; boundary=\(boundary)", forHTTPHeaderField: "Content-Type")
let postBody:NSMutableData = NSMutableData()
var postData:String = String()
postData += "--\(boundary)\r\n"
postData += "Content-Disposition: form-data; name=\"\(fieldName)\"; filename=\"\(Int64(Date().timeIntervalSince1970*1000)).jpg\"\r\n"
postData += "Content-Type: image/jpeg\r\n\r\n"
postBody.append(postData.data(using: String.Encoding.utf8)!)
postBody.append(imageData!)
postData = String()
postData += "\r\n"
postData += "\r\n--\(boundary)--\r\n"
postBody.append(postData.data(using: String.Encoding.utf8)!)
request.httpBody = NSData(data: postBody as Data) as Data
let session = URLSession.shared
let task = session.dataTask(with: request as URLRequest) {
(data, response, error) in
let httpResponse = response as! HTTPURLResponse
if httpResponse.statusCode >= 200 && httpResponse.statusCode < 300
{
guard let _:Data = data, let _:URLResponse = response , error
== nil else {
print("error")
return
}
self.uploadSuccessful()
}
else
{
let dataString = String(data: data!, encoding:
String.Encoding(rawValue: String.Encoding.utf8.rawValue))
print(dataString!)
self.uploadFailed(errorMessage: dataString!)
}
}
task.resume()
}
else
{
uploadFailed(errorMessage: "No Data")
}
}
以下是我要回复的回复:
<NSHTTPURLResponse: 0x7a6e4c80> { URL: http://url.com/images/up?docType=Image&docId=100&comment=Jhsgfdhsj } { status code: 500, headers {
"Cache-Control" = "no-cache";
Connection = "keep-alive";
"Content-Length" = 36;
"Content-Type" = "application/json; charset=utf-8";
Date = "Mon, 30 Jan 2017 16:17:22 GMT";
Expires = "-1";
Pragma = "no-cache";
Server = "Microsoft-IIS/8.5";
"X-AspNet-Version" = "4.0.30319";
"X-Powered-By" = "ASP.NET";
} }
网址正确,因为相同的网址在Android上工作正常。我甚至不知道代码有什么问题。请帮我解决一下。
答案 0 :(得分:0)
压缩是这里的问题。我不得不将图像压缩从1更改为0.5。