Xcode Allow User to Upload Multiple Images
268 votes
1 answers
ios - Xcode Swift/PHP/SQL upload multiple images failed
Get the solution ↓↓↓
I am learning "posting images to server", only when I tried the multiple images uploading, it always failed with reporting(JSON error, from my Xcode warning on iOS devices), it seems error is in the PHP side? But I am new, so anyone tin can aid me to detect whatever solution. Xcode:
-
httpBody function
func createBodyWithParameters(parameters: [String : Any]?,boundary: String) -> NSData { let body = NSMutableData()
if parameters != nil { for (primal, value) in parameters! { body.append("--\(boundary)\r\due north".data(using: .utf8)!) body.append("Content-Disposition: grade-information; name=\"\(primal)\"\r\n\r\north".data(using: .utf8)!) body.append("\(value)\r\n".data(using: .utf8)!) } } for prototype in images { allow filename = "\(NSUUID().uuidString).jpg" let imageData = image.jpegData(compressionQuality: ane) permit lineOne = "--" + purlieus + "\r\n" body.append(lineOne.data(using: .utf8, allowLossyConversion: faux)!) permit lineTwo = "Content-Disposition: form-data; name=\"files\"; filename=\"\(filename)\"\r\n" body.append(lineTwo.data(using: .utf8, allowLossyConversion: false)!) let lineThree = "Content-Type: epitome/jpg\r\n\r\northward" torso.suspend(lineThree.data(using: .utf8, allowLossyConversion: false)!) body.append(imageData!) permit lineFive = "\r\n" body.append(lineFive.data(using: .utf8, allowLossyConversion: false)!) } permit lineSix = "--" + boundary + "--\r\north" body.append(lineSix.data(using: .utf8, allowLossyConversion: false)!) return body
}
-
http asking function
func createRequest(parameters: [String : Whatsoever] , url : URL) -> URLRequest { var request = URLRequest(url: url) request.httpMethod = "Postal service" let boundary = "Boundary-\(NSUUID().uuidString)" request.setValue("multipart/form-data; boundary=\(boundary)", forHTTPHeaderField: "Content-Type") request.httpBody = createBodyWithParameters(parameters: parameters, boundary: boundary) as Data return asking
}
-
multi images upload functions func uploadPostWithMultipleImages() {
guard allow id = currentUser?["id"], let text = postTextView.text else { render } // declaring keys and values to be sent to the server let parameters = ["user_id": id, "text": text, "files": images] // declaring URL and request let url = URL(string: "http://localhost/projectExample/uploadPostMultipleImages.php")! let request = createRequest(parameters: parameters, url: url) URLSession.shared.dataTask(with: request) { (information, response, error) in DispatchQueue.main.async { // if error if fault != zippo { Helper().showAlert(title: "Server Mistake", message: error!.localizedDescription, in: cocky) return } // admission data / json exercise { // safe fashion of accessing received data from the server guard let data = data else { Helper().showAlert(title: "Data Error", bulletin: error!.localizedDescription, in: cocky) return } // converting information to JSON let json = try JSONSerialization.jsonObject(with: data, options: .allowFragments) every bit? NSDictionary // safe mode of accessing / casting JSON guard let parsedJSON = json else { render } // if post is uploaded successfully -> come back to HomeVC, else -> evidence error message if parsedJSON["status"] as! String == "200" { // post notification in gild to update the posts of the user in other viewControllers NotificationCenter.default.mail service(name: NSNotification.Name(rawValue: "uploadPost"), object: naught) // improvement self.dismiss(animated: true, completion: aught) } else { Helper().showAlert(title: "Error", message: parsedJSON["bulletin"] every bit! String, in: self) return } // error while accessing data / json } catch { Helper().showAlert(title: "JSON Error", message: mistake.localizedDescription, in: self) render } } }.resume()
}
-
PHP upload code
// generating accented path to the binder for every user with his unique id
$binder = '/Applications/XAMPP/xamppfiles/htdocs/projectExample/posts/' . $user_id;
// creating fodler if it doesn't exist if (!file_exists($folder)) { mkdir($folder, 0777, true); } else { $return['folder_message'] = 'Could not create a directory'; }
foreach($_FILES['files']['name'] every bit $key =>$value) { $file = $_FILES['files']['name'][$cardinal]; $file_tmp = $_FILES['files']['tmp_name'][$fundamental]; // path to the file. Full path of the file $path = $folder . '/' . basename($file); if (move_uploaded_file($file_tmp, $path)) { // creating URL link to the prototype uploaded $pictures .= 'http://localhost/projectExample/posts/' . $user_id . '/' . $file. " "; $return['pictures'] = $pictures; }
}//foreach
// Insert details into database $consequence = $access->insertPost($user_id, $text, $pictures);
Undefined asked
55
votes
Answer
Solution:
I utilise your swift code and upload images successfully, so I am certain it's your PHP code that has some mistake. please brand sure that you lot have return a json that is correctly-formatted like :
echo '{"code" : 200}'
Undefined answered
Link to answer
Source
Share
Didn't detect the answer?
Our community is visited by hundreds of web development professionals every day. Inquire your question and get a quick respond for free.
Similar questions
Find the respond in similar questions on our website.
Write quick answer
Do you know the answer to this question? Write a quick response to it. With your assist, we will make our customs stronger.
About the technologies asked in this question
PHP
PHP (from the English language Hypertext Preprocessor - hypertext preprocessor) is a scripting programming language for developing spider web applications. Supported past well-nigh hosting providers, information technology is one of the most popular tools for creating dynamic websites. The PHP scripting language has gained wide popularity due to its processing speed, simplicity, cross-platform, functionality and distribution of source codes under its own license.
https://www.php.net/
Welcome to programmierfrage.com
programmierfrage.com is a question and answer site for professional web developers, programming enthusiasts and website builders. Site created and operated by the community. Together with yous, we create a complimentary library of detailed answers to whatever question on programming, web development, website creation and website administration.
Go answers to specific questions
Ask near the existent problem y'all are facing. Describe in particular what you are doing and what y'all desire to achieve.
Assist Others Solve Their Issues
Our goal is to create a stiff community in which anybody will support each other. If you find a question and know the respond to it, assist others with your knowledge.
Source: https://programmierfrage.com/items/xcode-swift-php-sql-upload-multiple-images-failed
0 Response to "Xcode Allow User to Upload Multiple Images"
Post a Comment