多部分函数出现 PHP 500 内部错误
Getting PHP 500 internal error on multipart function
我正在点击一个 API,它类似于聊天消息,我们可以在其中发送图像或 pdf 和普通文本形式的附件。当我将应用程序上传到 App Store 时,它运行良好,但当我昨天检查它时,API 现在在发送简单文本(无附件)时向我抛出错误。它显示“500 内部服务器错误”
API 函数:-
if arraymultipartObject.count > 0
{
for obj in arraymultipartObject{
if obj.image != nil {
let imagene = obj.image
let resizedImage = imagene?.compressImage()
profileImageData = UIImageJPEGRepresentation(resizedImage!,1.0)
SavedImgDataArr.addObjects(from: [profileImageData!])
SavedPDFDataArr.removeAllObjects()
}
else {
let pdf = obj.urlpdf
print(pdf)
sendpdfData = try! Data(contentsOf: URL(string: pdf!)!)//pdf?.data(using: .utf8)
// sendpdfData = NSData(data: pdfData) //NSData(data: UIImageJPEGRepresentation((resizedImage!), 1)!)
SavedPDFDataArr.addObjects(from: [sendpdfData!])
SavedImgDataArr.removeAllObjects()
}
}
}
print(selectedFileName)
var messagetext = (textfiledMessage.text?.trimmingCharacters(in: .newlines))!
if messagetext == "Type a message"
{
messagetext = ""
}
let dictionary = ["uuid":UUid,"device_id":devicetoken,"school_id":LoginUserInfo.sharedInstance.schoolId!, "to": toStr,"title": titleStr, "description": messagetext,"class_id": classId ,"section_id":SectionId,"particulars":particulars,"teacher_ids":teacherIDS, "student_ids":StudentIDs,"notice_type":noticeType]
print(dictionary)
let encoder = JSONEncoder()
if let jsonData = try? encoder.encode(dictionary) {
if let jsonString = String(data: jsonData, encoding: .utf8) {
// print(jsonString)
let cipher:String = CryptoHelper.encrypt(input:jsonString)!;
let NewEncryption = ["data":cipher]as [String:String]
// let NewEncryption = "data=\(cipher)"
print(NewEncryption)
let hmac_md5 = cipher.hmac(algorithm: .sha512, key: kHMACKey)
print("hmac",hmac_md5)
UserDefaults.standard.set(hmac_md5, forKey: Headerkey)
let urlString = BaseURl + KSCreateMessage
Singleton.sharedInstance.postApiMethodWithMultipleImage(parms: NewEncryption, url: urlString, ImgArr: SavedImgDataArr, pdfArr: SavedPDFDataArr, selectedFileExtension: selectedFileName, onCompilation:
{ (result) in
DispatchQueue.main.async {
ReusableClass.sharedInstance.hideActivityIndicator()
}
if result != nil
{
do {
let jsonData = try JSONSerialization.data(withJSONObject: result)
if let json = String(data: jsonData, encoding: .utf8) {
let Dict = function.convertToDictionary(text: json)! as NSDictionary
guard let data = Dict[KData] as? String
else
{
return
}
self.baseDict = data
}
}
catch {
}
guard let output = CryptoHelper.decrypt(input:self.baseDict)
else
{
return
}
print(output)
let mainDict = function.convertToDictionary(text: output)! as NSDictionary
let status = mainDict[KStatus] as! NSInteger
if(status == 1)
{.......}
单例Class 命中函数API:-
//MARK update image with single image
func postApiMethodWithMultipleImage(parms: [String:String], url: String, ImgArr: NSMutableArray?, pdfArr:NSMutableArray?,selectedFileExtension:String?, onCompilation: (@escaping ImgPostCompletionHandler)){
let myUrl = NSURL(string: url);
ReusableClass.sharedInstance.showActivityIndicator()
let request = NSMutableURLRequest(url:myUrl! as URL);
request.httpMethod = "POST";
let boundary = generateBoundaryString()
request.setValue("multipart/form-data; boundary=\(boundary)", forHTTPHeaderField: "Content-Type")
// request.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")
if UserDefaults.standard.value(forKey: "header") != nil {
request.addValue(UserDefaults.standard.value(forKey: "header") as! String, forHTTPHeaderField:"HMAC" )
print(UserDefaults.standard.value(forKey: "header") as! String)
}
if selectedFileExtension == "pdf" {
request.httpBody = (createBodyWithParameterPDFArray(parameters: parms,
filePathKey: "FileName",
pdfKeyArr: pdfArr,
boundary: boundary)) as Data
}
else if selectedFileExtension == "image" //|| selectedFileExtension == ""
{
request.httpBody = (createBodyWithParameter(parameters: parms,
filePathKey: "FileName",
profile_imageKey: ImgArr,
boundary: boundary)) as Data
}else { //here I'm this function things go wrong
request.httpBody = (createBodyWithParameterTEST(parameters: parms,
filePathKey: "FileName",
profile_imageKey: ImgArr,
boundary: boundary)) as Data
}
let task = URLSession.shared.dataTask(with: request as URLRequest) {
data, response, error in
ReusableClass.sharedInstance.hideActivityIndicator()
if error != nil {
print("error=\(error)")
var errorInfo = NSDictionary()
errorInfo = ["result" : "Failure", "message" : error?.localizedDescription as Any]
onCompilation(errorInfo)
return
}
// You can print out response object
print("******* response = \(response)")
// Print out reponse body
//let responseString = NSString(data: data!, encoding: String.Encoding.utf8.rawValue)
let responseString = NSString(data: data!, encoding: String.Encoding.utf8.rawValue)
print("****** response data = \(responseString!)")
do {
let json = try JSONSerialization.jsonObject(with: data!, options: []) as? NSDictionary
print(json!)
onCompilation(json!)
}catch
{
print(error)
}
}
task.resume()
}
PDF 函数:-
//pdf array
func createBodyWithParameterPDFArray(parameters: [String: String]?, filePathKey: String?, pdfKeyArr: NSMutableArray?,boundary: String) -> NSData {
let body = NSMutableData();
if parameters != nil
{
for (key, value) in parameters!
{
body.appendString(string: "--\(boundary)\r\n")
body.appendString(string: "Content-Disposition: form-data; name=\"\(key)\"\r\n\r\n")
body.appendString(string: "\(value)\r\n")
}
}
let mimetype = "application/pdf"
let filename = String(Int(Date().timeIntervalSince1970)) + "doc.pdf"
print("file name",filename)
//1
if(pdfKeyArr != nil){
for i in pdfKeyArr!{
body.appendString(string: "--\(boundary)\r\n")
body.appendString(string: "Content-Disposition: form-data; name=\"\("attachments[]")\"; filename=\"\(filename)\"\r\n")
body.appendString(string: "Content-Type: \(mimetype)\r\n\r\n")
if (pdfKeyArr != nil) {
body.append(i as! Data)
}
body.appendString(string: "\r\n")
body.appendString(string: "--\(boundary)--\r\n")
}
}
return body
}
图像多部分函数:-
func createBodyWithParameter(parameters: [String: String]?, filePathKey: String?, profile_imageKey: NSMutableArray?,boundary: String) -> NSData {
let body = NSMutableData();
if parameters != nil
{
for (key, value) in parameters!
{
body.appendString(string: "--\(boundary)\r\n")
body.appendString(string: "Content-Disposition: form-data; name=\"\(key)\"\r\n\r\n")
body.appendString(string: "\(value)\r\n")
}
}
let mimetype = "image/jpg"
let filename = String(Int(Date().timeIntervalSince1970)) + "Img.jpg"
print("file name",filename)
//1
if(profile_imageKey != nil){
for i in profile_imageKey!{
body.appendString(string: "--\(boundary)\r\n")
body.appendString(string: "Content-Disposition: form-data; name=\"\("attachments[]")\"; filename=\"\(filename)\"\r\n")
body.appendString(string: "Content-Type: \(mimetype)\r\n\r\n")
if (profile_imageKey != nil) {
body.append(i as! Data)
}
body.appendString(string: "\r\n")
body.appendString(string: "--\(boundary)--\r\n")
}
}
return body
}
简单文本函数(多部分):-
//test empty data and simple String
func createBodyWithParameterTEST(parameters: [String: String]?, filePathKey: String?, profile_imageKey: NSMutableArray?,boundary: String) -> NSData {
let body = NSMutableData();
if parameters != nil
{
for (key, value) in parameters!
{
body.appendString(string: "--\(boundary)\r\n")
body.appendString(string: "Content-Disposition: form-data; name=\"\(key)\"\r\n\r\n")
body.appendString(string: "\(value)\r\n")
}
}
let mimetype = "image/jpg"
let filename = String(Int(Date().timeIntervalSince1970)) + "Img.jpg"
print("file name",filename)
//1
if(profile_imageKey != nil){
for i in profile_imageKey!{
body.appendString(string: "--\(boundary)\r\n")
body.appendString(string: "Content-Disposition: form-data; name=\"\("attachments[]")\"; filename=\"\(filename)\"\r\n")
body.appendString(string: "Content-Type: \(mimetype)\r\n\r\n")
if (profile_imageKey != nil) {
body.append(i as! Data)
}
body.appendString(string: "\r\n")
body.appendString(string: "--\(boundary)--\r\n")
}
}
return body
}
这是错误:-
******* response = Optional(<NSHTTPURLResponse: 0x2800c4f20> { URL: https://demo.com/admin/index.php/api/chat/create_message } { Status Code: 500, Headers {
"Content-Length" = (
666
);
"Content-Type" = (
"text/html; charset=iso-8859-1"
);
Date = (
"Tue, 23 Jul 2019 11:27:56 GMT"
);
Server = (
Apache
);
} })
****** response data = <!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML 2.0//EN">
<html><head>
<title>500 Internal Server Error</title>
</head><body>
<h1>Internal Server Error</h1>
<p>The server encountered an internal error or
misconfiguration and was unable to complete
your request.</p>
<p>Please contact the server administrator at
webmaster@kakshase.com to inform them of the time this error occurred,
and the actions you performed just before this error.</p>
<p>More information about this error may be available
in the server error log.</p>
<p>Additionally, a 500 Internal Server Error
error was encountered while trying to use an ErrorDocument to handle the request.</p>
</body></html>
如果在 multipart 函数中只发送字符串而不是数据,则在检查 for 循环中的参数键值时必须使用 body.appendString(string: "--\(boundary)--\r\n")
完成 multipart 函数。
修复方法如下:-
//test empty data and simple String
func createBodyWithParameterTEST(parameters: [String: String]?, filePathKey: String?, profile_imageKey: NSMutableArray?,boundary: String) -> NSData {
let body = NSMutableData();
if parameters != nil
{
for (key, value) in parameters!
{
body.appendString(string: "--\(boundary)\r\n")
body.appendString(string: "Content-Disposition: form-data; name=\"\(key)\"\r\n\r\n")
body.appendString(string: "\(value)\r\n")
body.appendString(string: "--\(boundary)--\r\n") //Call Boundary here also so that if there is not data and only string you are sending this will complete the multipart funtion here
}
}
let mimetype = "image/jpg"
let filename = String(Int(Date().timeIntervalSince1970)) + "Img.jpg"
print("file name",filename)
//1
if(profile_imageKey != nil){
for i in profile_imageKey!{
body.appendString(string: "--\(boundary)\r\n")
body.appendString(string: "Content-Disposition: form-data; name=\"\("attachments[]")\"; filename=\"\(filename)\"\r\n")
body.appendString(string: "Content-Type: \(mimetype)\r\n\r\n")
if (profile_imageKey != nil) {
body.append(i as! Data)
}
body.appendString(string: "\r\n")
body.appendString(string: "--\(boundary)--\r\n")
}
}
return body
}
我正在点击一个 API,它类似于聊天消息,我们可以在其中发送图像或 pdf 和普通文本形式的附件。当我将应用程序上传到 App Store 时,它运行良好,但当我昨天检查它时,API 现在在发送简单文本(无附件)时向我抛出错误。它显示“500 内部服务器错误”
API 函数:-
if arraymultipartObject.count > 0
{
for obj in arraymultipartObject{
if obj.image != nil {
let imagene = obj.image
let resizedImage = imagene?.compressImage()
profileImageData = UIImageJPEGRepresentation(resizedImage!,1.0)
SavedImgDataArr.addObjects(from: [profileImageData!])
SavedPDFDataArr.removeAllObjects()
}
else {
let pdf = obj.urlpdf
print(pdf)
sendpdfData = try! Data(contentsOf: URL(string: pdf!)!)//pdf?.data(using: .utf8)
// sendpdfData = NSData(data: pdfData) //NSData(data: UIImageJPEGRepresentation((resizedImage!), 1)!)
SavedPDFDataArr.addObjects(from: [sendpdfData!])
SavedImgDataArr.removeAllObjects()
}
}
}
print(selectedFileName)
var messagetext = (textfiledMessage.text?.trimmingCharacters(in: .newlines))!
if messagetext == "Type a message"
{
messagetext = ""
}
let dictionary = ["uuid":UUid,"device_id":devicetoken,"school_id":LoginUserInfo.sharedInstance.schoolId!, "to": toStr,"title": titleStr, "description": messagetext,"class_id": classId ,"section_id":SectionId,"particulars":particulars,"teacher_ids":teacherIDS, "student_ids":StudentIDs,"notice_type":noticeType]
print(dictionary)
let encoder = JSONEncoder()
if let jsonData = try? encoder.encode(dictionary) {
if let jsonString = String(data: jsonData, encoding: .utf8) {
// print(jsonString)
let cipher:String = CryptoHelper.encrypt(input:jsonString)!;
let NewEncryption = ["data":cipher]as [String:String]
// let NewEncryption = "data=\(cipher)"
print(NewEncryption)
let hmac_md5 = cipher.hmac(algorithm: .sha512, key: kHMACKey)
print("hmac",hmac_md5)
UserDefaults.standard.set(hmac_md5, forKey: Headerkey)
let urlString = BaseURl + KSCreateMessage
Singleton.sharedInstance.postApiMethodWithMultipleImage(parms: NewEncryption, url: urlString, ImgArr: SavedImgDataArr, pdfArr: SavedPDFDataArr, selectedFileExtension: selectedFileName, onCompilation:
{ (result) in
DispatchQueue.main.async {
ReusableClass.sharedInstance.hideActivityIndicator()
}
if result != nil
{
do {
let jsonData = try JSONSerialization.data(withJSONObject: result)
if let json = String(data: jsonData, encoding: .utf8) {
let Dict = function.convertToDictionary(text: json)! as NSDictionary
guard let data = Dict[KData] as? String
else
{
return
}
self.baseDict = data
}
}
catch {
}
guard let output = CryptoHelper.decrypt(input:self.baseDict)
else
{
return
}
print(output)
let mainDict = function.convertToDictionary(text: output)! as NSDictionary
let status = mainDict[KStatus] as! NSInteger
if(status == 1)
{.......}
单例Class 命中函数API:-
//MARK update image with single image
func postApiMethodWithMultipleImage(parms: [String:String], url: String, ImgArr: NSMutableArray?, pdfArr:NSMutableArray?,selectedFileExtension:String?, onCompilation: (@escaping ImgPostCompletionHandler)){
let myUrl = NSURL(string: url);
ReusableClass.sharedInstance.showActivityIndicator()
let request = NSMutableURLRequest(url:myUrl! as URL);
request.httpMethod = "POST";
let boundary = generateBoundaryString()
request.setValue("multipart/form-data; boundary=\(boundary)", forHTTPHeaderField: "Content-Type")
// request.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")
if UserDefaults.standard.value(forKey: "header") != nil {
request.addValue(UserDefaults.standard.value(forKey: "header") as! String, forHTTPHeaderField:"HMAC" )
print(UserDefaults.standard.value(forKey: "header") as! String)
}
if selectedFileExtension == "pdf" {
request.httpBody = (createBodyWithParameterPDFArray(parameters: parms,
filePathKey: "FileName",
pdfKeyArr: pdfArr,
boundary: boundary)) as Data
}
else if selectedFileExtension == "image" //|| selectedFileExtension == ""
{
request.httpBody = (createBodyWithParameter(parameters: parms,
filePathKey: "FileName",
profile_imageKey: ImgArr,
boundary: boundary)) as Data
}else { //here I'm this function things go wrong
request.httpBody = (createBodyWithParameterTEST(parameters: parms,
filePathKey: "FileName",
profile_imageKey: ImgArr,
boundary: boundary)) as Data
}
let task = URLSession.shared.dataTask(with: request as URLRequest) {
data, response, error in
ReusableClass.sharedInstance.hideActivityIndicator()
if error != nil {
print("error=\(error)")
var errorInfo = NSDictionary()
errorInfo = ["result" : "Failure", "message" : error?.localizedDescription as Any]
onCompilation(errorInfo)
return
}
// You can print out response object
print("******* response = \(response)")
// Print out reponse body
//let responseString = NSString(data: data!, encoding: String.Encoding.utf8.rawValue)
let responseString = NSString(data: data!, encoding: String.Encoding.utf8.rawValue)
print("****** response data = \(responseString!)")
do {
let json = try JSONSerialization.jsonObject(with: data!, options: []) as? NSDictionary
print(json!)
onCompilation(json!)
}catch
{
print(error)
}
}
task.resume()
}
PDF 函数:-
//pdf array
func createBodyWithParameterPDFArray(parameters: [String: String]?, filePathKey: String?, pdfKeyArr: NSMutableArray?,boundary: String) -> NSData {
let body = NSMutableData();
if parameters != nil
{
for (key, value) in parameters!
{
body.appendString(string: "--\(boundary)\r\n")
body.appendString(string: "Content-Disposition: form-data; name=\"\(key)\"\r\n\r\n")
body.appendString(string: "\(value)\r\n")
}
}
let mimetype = "application/pdf"
let filename = String(Int(Date().timeIntervalSince1970)) + "doc.pdf"
print("file name",filename)
//1
if(pdfKeyArr != nil){
for i in pdfKeyArr!{
body.appendString(string: "--\(boundary)\r\n")
body.appendString(string: "Content-Disposition: form-data; name=\"\("attachments[]")\"; filename=\"\(filename)\"\r\n")
body.appendString(string: "Content-Type: \(mimetype)\r\n\r\n")
if (pdfKeyArr != nil) {
body.append(i as! Data)
}
body.appendString(string: "\r\n")
body.appendString(string: "--\(boundary)--\r\n")
}
}
return body
}
图像多部分函数:-
func createBodyWithParameter(parameters: [String: String]?, filePathKey: String?, profile_imageKey: NSMutableArray?,boundary: String) -> NSData {
let body = NSMutableData();
if parameters != nil
{
for (key, value) in parameters!
{
body.appendString(string: "--\(boundary)\r\n")
body.appendString(string: "Content-Disposition: form-data; name=\"\(key)\"\r\n\r\n")
body.appendString(string: "\(value)\r\n")
}
}
let mimetype = "image/jpg"
let filename = String(Int(Date().timeIntervalSince1970)) + "Img.jpg"
print("file name",filename)
//1
if(profile_imageKey != nil){
for i in profile_imageKey!{
body.appendString(string: "--\(boundary)\r\n")
body.appendString(string: "Content-Disposition: form-data; name=\"\("attachments[]")\"; filename=\"\(filename)\"\r\n")
body.appendString(string: "Content-Type: \(mimetype)\r\n\r\n")
if (profile_imageKey != nil) {
body.append(i as! Data)
}
body.appendString(string: "\r\n")
body.appendString(string: "--\(boundary)--\r\n")
}
}
return body
}
简单文本函数(多部分):-
//test empty data and simple String
func createBodyWithParameterTEST(parameters: [String: String]?, filePathKey: String?, profile_imageKey: NSMutableArray?,boundary: String) -> NSData {
let body = NSMutableData();
if parameters != nil
{
for (key, value) in parameters!
{
body.appendString(string: "--\(boundary)\r\n")
body.appendString(string: "Content-Disposition: form-data; name=\"\(key)\"\r\n\r\n")
body.appendString(string: "\(value)\r\n")
}
}
let mimetype = "image/jpg"
let filename = String(Int(Date().timeIntervalSince1970)) + "Img.jpg"
print("file name",filename)
//1
if(profile_imageKey != nil){
for i in profile_imageKey!{
body.appendString(string: "--\(boundary)\r\n")
body.appendString(string: "Content-Disposition: form-data; name=\"\("attachments[]")\"; filename=\"\(filename)\"\r\n")
body.appendString(string: "Content-Type: \(mimetype)\r\n\r\n")
if (profile_imageKey != nil) {
body.append(i as! Data)
}
body.appendString(string: "\r\n")
body.appendString(string: "--\(boundary)--\r\n")
}
}
return body
}
这是错误:-
******* response = Optional(<NSHTTPURLResponse: 0x2800c4f20> { URL: https://demo.com/admin/index.php/api/chat/create_message } { Status Code: 500, Headers {
"Content-Length" = (
666
);
"Content-Type" = (
"text/html; charset=iso-8859-1"
);
Date = (
"Tue, 23 Jul 2019 11:27:56 GMT"
);
Server = (
Apache
);
} })
****** response data = <!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML 2.0//EN">
<html><head>
<title>500 Internal Server Error</title>
</head><body>
<h1>Internal Server Error</h1>
<p>The server encountered an internal error or
misconfiguration and was unable to complete
your request.</p>
<p>Please contact the server administrator at
webmaster@kakshase.com to inform them of the time this error occurred,
and the actions you performed just before this error.</p>
<p>More information about this error may be available
in the server error log.</p>
<p>Additionally, a 500 Internal Server Error
error was encountered while trying to use an ErrorDocument to handle the request.</p>
</body></html>
如果在 multipart 函数中只发送字符串而不是数据,则在检查 for 循环中的参数键值时必须使用 body.appendString(string: "--\(boundary)--\r\n")
完成 multipart 函数。
修复方法如下:-
//test empty data and simple String
func createBodyWithParameterTEST(parameters: [String: String]?, filePathKey: String?, profile_imageKey: NSMutableArray?,boundary: String) -> NSData {
let body = NSMutableData();
if parameters != nil
{
for (key, value) in parameters!
{
body.appendString(string: "--\(boundary)\r\n")
body.appendString(string: "Content-Disposition: form-data; name=\"\(key)\"\r\n\r\n")
body.appendString(string: "\(value)\r\n")
body.appendString(string: "--\(boundary)--\r\n") //Call Boundary here also so that if there is not data and only string you are sending this will complete the multipart funtion here
}
}
let mimetype = "image/jpg"
let filename = String(Int(Date().timeIntervalSince1970)) + "Img.jpg"
print("file name",filename)
//1
if(profile_imageKey != nil){
for i in profile_imageKey!{
body.appendString(string: "--\(boundary)\r\n")
body.appendString(string: "Content-Disposition: form-data; name=\"\("attachments[]")\"; filename=\"\(filename)\"\r\n")
body.appendString(string: "Content-Type: \(mimetype)\r\n\r\n")
if (profile_imageKey != nil) {
body.append(i as! Data)
}
body.appendString(string: "\r\n")
body.appendString(string: "--\(boundary)--\r\n")
}
}
return body
}