我尝试使用REST API将UIImage上传到网络服务器,我收到500错误。 swift代码或php代码有什么问题吗?我在网络服务器上找不到任何错误。
func UploadRequest(image: UIImage)
{
let url = NSURL(string: "https://server-to-upload-file.com")
let request = NSMutableURLRequest(url: url! as URL)
request.httpMethod = "POST"
let boundary = generateBoundaryString()
//define the multipart request type
request.setValue("multipart/form-data; boundary=\(boundary)", forHTTPHeaderField: "Content-Type")
if (image == nil)
{
return
}
let image_data = UIImageJPEGRepresentation(image, 1)
if(image_data == nil)
{
return
}
let body = NSMutableData()
let fname = "test.png"
let mimetype = "image/png"
//define the data post parameter
body.append("--\(boundary)\r\n".data(using: String.Encoding.utf8)!)
body.append("Content-Disposition:form-data; name=\"test\"\r\n\r\n".data(using: String.Encoding.utf8)!)
body.append("hi\r\n".data(using: String.Encoding.utf8)!)
body.append("--\(boundary)\r\n".data(using: String.Encoding.utf8)!)
body.append("Content-Disposition:form-data; name=\"file\"; filename=\"\(fname)\"\r\n".data(using: String.Encoding.utf8)!)
body.append("Content-Type: \(mimetype)\r\n\r\n".data(using: String.Encoding.utf8)!)
body.append(image_data!)
body.append("\r\n".data(using: String.Encoding.utf8)!)
body.append("--\(boundary)--\r\n".data(using: String.Encoding.utf8)!)
request.httpBody = body as Data
let session = URLSession.shared
let task = session.dataTask(with: request as URLRequest) {
(
data, response, error) in
guard let _:NSData = data as NSData?, let _:URLResponse = response , error == nil else {
print("error")
return
}
let dataString = NSString(data: data!, encoding: String.Encoding.utf8.rawValue)
print(dataString)
}
task.resume()
}
func generateBoundaryString() -> String
{
return "Boundary-\(NSUUID().uuidString)"
}
答案 0 :(得分:0)
错误代码500是服务器错误。基本上,服务器代码中的任何异常都会产生此代码 我试图说你的服务器代码是正确的,并且因为从iOS设备发送错误的数据而崩溃,或者你正在以正确的格式发送数据,但你的服务器没有正确接收它。
您应该阅读服务器的错误日志以了解更多信息。