I am trying to upload an image using Alamofire and PHP on my server, I checked all the different questions on here but for some reason it wont work. I have tested my PHP file with HTML and it succeeded in uploading an image, so it narrows down to my swift code.
Swift:
let URL = "http://example.com/post_pic.php"
let imageData = UIImageJPEGRepresentation(imageView.image!, 1)
Alamofire.upload(multipartFormData: { (multipartFormData) in
multipartFormData.append(imageData!, withName: "imageFile", mimeType: "image/jpeg")
}, to:URL)
{ (result) in
switch result {
case .success(let upload, _, _):
upload.uploadProgress(closure: { (Progress) in
print("Upload Progress: \(Progress.fractionCompleted)")
})
upload.responseJSON { response in
print(response.request) // original URL request
print(response.response) // URL response
print(response.data) // server data
print(response.result) // result of response serialization
// self.showSuccesAlert()
//self.removeImage("frame", fileExtension: "txt")
if let JSON = response.result.value {
print("JSON: \(JSON)")
}
}
case .failure(let encodingError):
print("Failure:")
print(encodingError)
}
}
PHP:
if(isset($_FILES['imageFile'])){
$errors= array();
$file_name = $_FILES['imageFile']['name'];
$file_size =$_FILES['imageFile']['size'];
$file_tmp =$_FILES['imageFile']['tmp_name'];
$file_type=$_FILES['imageFile']['type'];
$file_ext=strtolower(end(explode('.',$_FILES['imageFile']['name'])));
print_r($_FILES['imageFile']);
if(empty($errors)==true){
move_uploaded_file($file_tmp,"images/".$file_name);
}
else
{
echo '{"response":"file_move_error"}';
}
}
else
{
echo '{"response":"file_error"}';
}
The response I get is:
Optional(<NSHTTPURLResponse: 0x17022df20> { URL: http://example.com/post_pic.php } {
status code: 200, headers {
Connection = "Keep-Alive";
"Content-Length" = 25;
"Content-Type" = "application/json";
Date = "Wed, 25 Jan 2017 10:16:29 GMT";
"Keep-Alive" = "timeout=5, max=100";
Server = "Apache/2.4.7 (Ubuntu)";
"X-Powered-By" = "PHP/5.5.9-1ubuntu4.20";
} })
Optional(25 bytes)
SUCCESS
JSON: {
response = "file_error";
}
I can use this code into my app
let URL = "http://example.com/post_pic.php"
let imageData = UIImageJPEGRepresentation(imageView.image!, 1)
upload(multipartFormData: { multipartFormData in
multipartFormData.append(imageData!, withName: "imageFile", fileName: "file.jpg", mimeType: "image/jpeg")
},
to: URL, method: .post,
encodingCompletion: { encodingResult in
switch encodingResult {
case .success(let upload, _, _):
upload.validate()
upload.responseJSON { response in
if response.result.error != nil {
print("failure")
UIAlertView(title: "Fail", message: "Please retry again.", delegate: nil, cancelButtonTitle: "Ok").show()
} else {
print("success")
}
}
case .failure(let encodingError):
print(encodingError)
}
}
)
Related
I am learning "posting images to server", but when I tried the multiple images uploading, it always failed with reporting(JSON error, from my Xcode alert on iOS devices), it seems error is in the PHP side? But I am new, so anyone can help me to find any solution.
Xcode:
httpBody function
func createBodyWithParameters(parameters: [String : Any]?,boundary: String) -> NSData {
let body = NSMutableData()
if parameters != nil {
for (key, value) in parameters! {
body.append("--\(boundary)\r\n".data(using: .utf8)!)
body.append("Content-Disposition: form-data; name=\"\(key)\"\r\n\r\n".data(using: .utf8)!)
body.append("\(value)\r\n".data(using: .utf8)!)
}
}
for image in images {
let filename = "\(NSUUID().uuidString).jpg"
let imageData = image.jpegData(compressionQuality: 1)
let lineOne = "--" + boundary + "\r\n"
body.append(lineOne.data(using: .utf8, allowLossyConversion: false)!)
let lineTwo = "Content-Disposition: form-data; name=\"files\"; filename=\"\(filename)\"\r\n"
body.append(lineTwo.data(using: .utf8, allowLossyConversion: false)!)
let lineThree = "Content-Type: image/jpg\r\n\r\n"
body.append(lineThree.data(using: .utf8, allowLossyConversion: false)!)
body.append(imageData!)
let lineFive = "\r\n"
body.append(lineFive.data(using: .utf8, allowLossyConversion: false)!)
}
let lineSix = "--" + boundary + "--\r\n"
body.append(lineSix.data(using: .utf8, allowLossyConversion: false)!)
return body
}
http request function
func createRequest(parameters: [String : Any] , url : URL) -> URLRequest {
var request = URLRequest(url: url)
request.httpMethod = "POST"
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 request
}
multi images upload functions
func uploadPostWithMultipleImages() {
guard let id = currentUser?["id"], let text = postTextView.text else {
return
}
// 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) { (data, response, error) in
DispatchQueue.main.async {
// if error
if error != nil {
Helper().showAlert(title: "Server Error", message: error!.localizedDescription, in: self)
return
}
// access data / json
do {
// safe mode of accessing received data from the server
guard let data = data else {
Helper().showAlert(title: "Data Error", message: error!.localizedDescription, in: self)
return
}
// converting data to JSON
let json = try JSONSerialization.jsonObject(with: data, options: .allowFragments) as? NSDictionary
// safe mode of accessing / casting JSON
guard let parsedJSON = json else {
return
}
// if post is uploaded successfully -> come back to HomeVC, else -> show error message
if parsedJSON["status"] as! String == "200" {
// post notification in order to update the posts of the user in other viewControllers
NotificationCenter.default.post(name: NSNotification.Name(rawValue: "uploadPost"), object: nil)
// comeback
self.dismiss(animated: true, completion: nil)
} else {
Helper().showAlert(title: "Error", message: parsedJSON["message"] as! String, in: self)
return
}
// error while accessing data / json
} catch {
Helper().showAlert(title: "JSON Error", message: error.localizedDescription, in: self)
return
}
}
}.resume()
}
PHP upload code
// generating absolute path to the folder for every user with his unique id
$folder = '/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'] as $key =>$value) {
$file = $_FILES['files']['name'][$key];
$file_tmp = $_FILES['files']['tmp_name'][$key];
// 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 image uploaded
$pictures .= 'http://localhost/projectExample/posts/' . $user_id . '/' . $file. " ";
$return['pictures'] = $pictures;
}
}//foreach
// Insert details into database
$result = $access->insertPost($user_id, $text, $pictures);
I use your swift code and upload images successfully, so I am sure it's your PHP code that has some error. please make sure that you have return a json that is correctly-formatted like :
echo '{"code" : 200}'
I have an IOS app that uses PHP for my API. My file upload is working fine but the name of the file is not appending to the file. I've mirrored other pages in my app but it's still not working although others are working fine. I’m able to see the file on the server, but the name is notes-.jpg. It’s not appending the puuid to the name per the code. I've implemented MessageKit on the ViewController that isn't working (just in case it makes a difference). Here is my code below, I feel like I'm looking for a needle in a haystack. The code is a little sloppy (please don't judge).
func createBodyWithParams(_ parameters: [String: String]?, filePathKey: String?, imageDataKey: Data, boundary: String) -> Data {
let body = NSMutableData();
if parameters != nil {
for (key, value) in parameters! {
body.appendString("--\(boundary)\r\n")
body.appendString("Content-Disposition: form-data; name=\"\(key)\"\r\n\r\n")
body.appendString("\(value)\r\n")
}
}
// if file is not selected, it will not upload a file to server, because we did not declare a name file
var filename = ""
if imageSelected == true {
filename = "notes-\(puuid).jpg"
print("name of file", filename)
}
let mimetype = "image/jpg"
body.appendString("--\(boundary)\r\n")
body.appendString("Content-Disposition: form-data; name=\"\(filePathKey!)\"; filename=\"\(filename)\"\r\n")
body.appendString("Content-Type: \(mimetype)\r\n\r\n")
body.append(imageDataKey)
body.appendString("\r\n")
body.appendString("--\(boundary)--\r\n")
return body as Data
}
func uploadImage(_ image: UIImage, completion: #escaping (URL?) -> Void) {
print("im in upload")
let avame = user!["ava"]
let user_id = user!["id"] as! String
let me = user!["username"] as! String
let recipientfe = getmessages["recipient"]
let uuidfe = getmessages["uuid"] as! String
let recipient = getmessages["username"] as! String
let rid = String(describing: getmessages["sender_id"]!)
let puuid = UUID().uuidString
let text = ""
let url = URL(string: "https://localhost/messagepost.php")!
var request = URLRequest(url: url)
request.httpMethod = "POST"
let parameters = ["sender_id": user_id, "uuid": uuidfe, "sender": me, "recipient_id": rid, "recipient": recipient, "puuid": puuid, "text": text]
let boundary = "Boundary-\(UUID().uuidString)"
request.setValue("multipart/form-data; boundary=\(boundary)", forHTTPHeaderField: "Content-Type")
var data = Data()
if image != nil {
data = image.jpegData(compressionQuality: 0.5)!
}
request.httpBody = createBodyWithParams(parameters, filePathKey: "file", imageDataKey: data, boundary: boundary)
URLSession.shared.dataTask(with: request) { data, response, error in
DispatchQueue.main.async(execute: {
if error != nil {
Helper().showAlert(title: "Server Error", message: error!.localizedDescription, in: self)
print("Server Error")
return
}
do {
guard let data = data else {
Helper().showAlert(title: "Data Error", message: error!.localizedDescription, in: self)
print("Data Error")
return
}
let json = try JSONSerialization.jsonObject(with: data, options: .allowFragments) as? NSDictionary
guard let parsedJSON = json else {
return
}
if parsedJSON["status"] as! String == "200" {
let newurl = parsedJSON["path"]
self.isSendingPhoto = true
guard let url = newurl else {
return
}
var message = Message(messageuser: self.sender, image: image)
message.downloadURL = url as? URL
self.save(message)
self.messagesCollectionView.scrollToBottom()
} else {
if parsedJSON["message"] != nil {
let message = parsedJSON["message"] as! String
Helper().showAlert(title: "Error", message: message, in: self)
print("where am i", parsedJSON["message"] as Any)
}
}
} catch {
Helper().showAlert(title: "JSON Error", message: error.localizedDescription, in: self)
print("where am i 2")
}
})
}.resume()
}
PHP Upload File
<?php
if (!empty($_REQUEST["uuid"])) {
$id = htmlentities($_REQUEST["id"]);
$recipient = htmlentities($_REQUEST["recipient"]);
$recipient_id = htmlentities($_REQUEST["recipient_id"]);
$uuid = htmlentities($_REQUEST["uuid"]);
$puuid = htmlentities($_REQUEST["puuid"]);
$text = htmlentities($_REQUEST["text"]);
$sender = htmlentities($_REQUEST["sender"]);
$sender_id = htmlentities($_REQUEST["sender_id"]);
if (isset($_FILES['file']) && $_FILES['file']['size'] > 1) {
$folder = "/home/xxxxx/public_html/notes/" . $uuid;
// if no posts folder, create it
if (!file_exists($folder)) {
mkdir($folder, 0777, true);
}
$picture = $folder . "/" . basename($_FILES["file"]["name"]);
chmod($picture,0777);
if (move_uploaded_file($_FILES["file"]["tmp_name"], $picture)) {
$path = "http://localhost/notes/" . $uuid . "/notes-" . $puuid . ".jpg";
$returnArray["message"] = "Post has been made with picture";
$returnArray["path"] = $path;
$returnArray["status"] = "200";
} else {
$returnArray["message"] = "Post has been made without picture";
$path = "";
}
$result=$access->insertMessage($recipient, $recipient_id, $uuid, $sender,$sender_id, $text, $path);
// STEP 2.5 If posts are found, append them to $returnArray
if (!empty($result)) {
$returnArray["message"] = $result;
$result = $access->updatebadge($recipient_id);
}
else {
$returnArray["message"] = "Couldnt insert". $puuid ."";
}
// if data is not passed - show posts except id of the user
}
else {
$username = htmlentities($_REQUEST["username"]);
$uuid = htmlentities($_REQUEST["uuid"]);
$recipient_id = htmlentities($_REQUEST["recipient_id"]);
$message = $access->conversation($username, $uuid, $recipient_id);
if (!empty($message)) {
$returnArray["message"] = $message;
}
}
}
$access->disconnect();
echo json_encode($returnArray);
?>
I figured it out. The body and headers in Swift were incorrect and weren't sending the correct file name.
I changed the body to:
// web development and MIME Type of passing information to the web server
let boundary = "Boundary-\(NSUUID().uuidString)"
request.setValue("multipart/form-data; boundary=\(boundary)", forHTTPHeaderField: "Content-Type")
// access / convert image to Data for sending to the server
var data = Data()
// if picture has been selected, compress the picture before sending to the server
if image != nil {
data = image.jpegData(compressionQuality: 0.5)!
}
// building the full body along with the string, text, file parameters
request.httpBody = Helper().body(with: parameters, filename: "notes-\(puuid).jpg", filePathKey: "file", imageDataKey: data, boundary: boundary) as Data
I am trying to just upload one image to my server but my code is not working.Here is my swift code:
import UIKit
import Alamofire
import SwiftyJSON
class ViewController: UIViewController {
#IBOutlet weak var theOneImage: UIImageView!
let url = "http://xxx.xxx.xxx.xxx/Twitter/UploadImage.php"
let avaImage = UIImage(named: "cupid")
override func viewDidLoad() {
super.viewDidLoad()
theOneImage.image = avaImage
uploadImage(image: avaImage)
}
func uploadImage(image : UIImage?){
let imageData = avaImage?.pngData()
Alamofire.upload(multipartFormData: { (MultipartFormData) in
MultipartFormData.append(imageData!, withName: "image")
}, to: url) { (encodingResult) in
switch encodingResult{
case .success(let upload, _, _):
upload.responseJSON{ response in
print(response.request!) // original URL request
print(response.response!) // URL response
print(response.data!) // server data
print(response.result) // result of response serialization
if let JSON = response.result.value {
print("JSON: \(JSON)")
}
}
case .failure(let encodingError):
print(encodingError)
}
}
}
}
here is my php code:
if (empty($_FILES["image"])){
$response = array("error" => "no data");
}else{
$response["error"] = "NULL";
$filename = uniqid() . ".jpg";
if(move_uploaded_file($_FILES['image']['test'],'/ava')){
$response["status"] = "success";
$response["filepath"] = "http:" . $filename;
$response["filename"] = "" . $_FILES["file"]["name"];
}else{
$response['status'] = "Failure";
$response['error'] = "".$_FILES["image"]["error"];
$response['name'] = "".$_FILES["image"]["name"];
$response['path'] = "".$_FILES["image"]["tmp_name"];
$response['type'] = "".$_FILES["image"]["type"];
$response['size'] = "".$_FILES["image"]["size"];
}
}
echo json_encode($response);
the response I am getting is telling me that in UploadImage.php, $_FILE["image"] is empty
here is my directories of my server:
server screen shot
please help. Thank you all!
I want to upload multiple images to my server using Alamofire Lib, but it's uploading 1 image only.
I'm using an image picker that returns an array of UIImage which is Named
imagesdata
This is my code:
#IBAction func uploadimages(_ sender: Any) {
Alamofire.upload(
multipartFormData: { multipartFormData in
for img in self.imagesdata{
let imgdata = UIImageJPEGRepresentation(img, 1.0)
multipartFormData.append(imgdata!,withName: "image", fileName: "image.jpg", mimeType: "image/jpeg")
print("$$$$$$$$$$ : \(imgdata!)")
}
},
to: "http://localhost/maarathtest/MAPI/img_upload.php",
encodingCompletion: { encodingResult in
switch encodingResult {
case .success(let upload, _, _):
upload.responseJSON { response in
debugPrint(response)
}
case .failure(let encodingError):
print(encodingError)
}
}
)
}
and my PHP:
<?php
$response = array();
if (empty($_FILES["image"])) {
$response['File'] = "NOFILE";;
} else {
$filename = uniqid() . ".jpg";
// If the server can move the temporary uploaded file to the server
if (move_uploaded_file($_FILES['image']['tmp_name'], "images/" . $filename)) {
$response['status'] = "Success";
$response['filepath'] = "https://serverName/MAPI/images/" . $filename;
} else {
$response['status'] = "Failure";
}
}
echo json_encode($response);
?>
And my console log:
$$$$$$$$$$ : 5849743 bytes
$$$$$$$$$$ : 3253337 bytes
[Request]: POST http://localhost/maarathtest/MAPI/img_upload.php
[Response]: <NSHTTPURLResponse: 0x600000620940> { URL: http://localhost/maarathtest/MAPI/img_upload.php } { status code: 200, headers {
Connection = "Keep-Alive";
"Content-Length" = 101;
"Content-Type" = "text/html";
Date = "Thu, 25 May 2017 10:08:08 GMT";
"Keep-Alive" = "timeout=5, max=100";
Server = "Apache/2.4.18 (Unix) OpenSSL/1.0.2h PHP/5.5.35 mod_perl/2.0.8-dev Perl/v5.16.3";
"X-Powered-By" = "PHP/5.5.35";
} }
[Data]: 101 bytes
[Result]: SUCCESS: {
filepath = "https://serverName/MAPI/images/5926ad083b770.jpg";
status = Success;
}
I have changed my code as below,
Alamofire.upload(
multipartFormData: { multipartFormData in
var count = 1
for img in self.imagesdata{
let imgdata = UIImageJPEGRepresentation(img, 1.0)
multipartFormData.append(imgdata!,withName: "image\(count)", fileName: "image\(count).jpg", mimeType: "image/jpeg")
count += 1
}
},...
<?php
$response = array();
if (empty($_FILES["image1"])) {
$response['File1'] = "NOFILE";
} else {
$filename = uniqid() . ".jpg";
// If the server can move the temporary uploaded file to the server
if (move_uploaded_file($_FILES['image1']['tmp_name'], "images/" . $filename)) {
$response['status1'] = "Success";
$response['filepath1'] = "https://serverName/MAPI/images/" . $filename;
} else {
$response['status1'] = "Failure";
}
}
if (empty($_FILES["image2"])) {
$response['File2'] = "NOFILE";
} else {
$filename = uniqid() . ".jpg";
// If the server can move the temporary uploaded file to the server
if (move_uploaded_file($_FILES['image2']['tmp_name'], "images/" . $filename)) {
$response['status2'] = "Success";
$response['filepath2'] = "https://serverName/MAPI/images/" . $filename;
} else {
$response['status2'] = "Failure";
}
}
echo json_encode($response);
?>
Now it's uploading the images, but I don't think this is the proper way to do it, since I don't know how many images users want to upload!
How can I do this properly?
I have solved the issue, the code below hope to help some 1
Swift :
#IBAction func uploadimages(_ sender: Any) {
Alamofire.upload(
multipartFormData: { multipartFormData in
var count = 1
for img in self.imagesdata{
let imgdata = UIImageJPEGRepresentation(img, 0.5)
// the name should be as array other wise want work
multipartFormData.append(imgdata!,withName: "image[]", fileName: "image\(count).jpg", mimeType: "image/jpeg")
count += 1
}
},
to: "http://localhost/maarathtest/MAPI/img_upload.php",
encodingCompletion: { encodingResult in
switch encodingResult {
case .success(let upload, _, _):
upload.responseJSON { response in
debugPrint(response)
}
case .failure(let encodingError):
print(encodingError)
}
}
)
}
PHP code sample :
<?php
$response = array();
if (empty($_FILES["image"])) {
$response['File1'] = "NOFILE";
}else {
//$filename = uniqid() . ".jpg";
// loop through files array from IOS app
foreach ($_FILES["image"]["tmp_name"] as $index => $tmp_name) {
$filePath = "images/" . basename($_FILES["image"]["name"][$index]);
if (move_uploaded_file($tmp_name, $filePath)) {
// Images are stored in file path , do what ever is needed
$response['filepath'][$index] = $filePath;
}
$response['status'] = "Success";
}
}
echo json_encode($response);
?>
Use this below code to upload multiple images to your server. I've put this in a method that takes in NSMutableArray of UIImage objects and their corresponding names in another array. You could change NSMutableArray to Swift Array if you want. After successful upload, the completion handler will get called and would return a mapped object based on your response:Code:
public func executeMultipleImageUpload<T: Mappable>(type: T.Type, url: String, parameters: Dictionary<String, String>, images: NSMutableArray?, names: [String], view: UIView, completion: #escaping(_ result: DataResponse<T>?)-> Void) {
//Calling Alamofire Upload method here...
Alamofire.upload(multipartFormData: { multipartFormData in // This is first param, the part data itself
if images == nil || images?.count == 0 {
print("There are no images to upload..!!")
} else {
//Append image data from array of images to multipart form data
var count = 1
for image in images! {
if let imageData = UIImageJPEGRepresentation(image as! UIImage, 0.76) {
multipartFormData.append(imageData, withName: names[count - 1], fileName: names[count - 1], mimeType: "image/jpeg")
}
count += 1
}
}
//We are encoding the parameters to be sent here in the multipart as well..
for (key, value) in parameters {
multipartFormData.append((value.data(using: .utf8))!, withName: key)
}}, to: url, method: .post, headers: ["": ""], //This is second param (to:)
encodingCompletion: { encodingResult in // This is third param (encodingCompletion:)
switch encodingResult {
case .success(let upload, _, _):
upload.response { [weak self] response in
guard self != nil else {
return
}
debugPrint(response)
}.validate().responseObject{
(response: DataResponse<T>) in
completion(response)
}
case .failure(let encodingError):
print("error:\(encodingError)")
}
})
}
I'm trying to upload an image to my web server from an ios app using PHP. I have the following code that manages the upload:
func uploadImage()
{
// get userId from saved credentials
let userId = UserDefaults.standard.string(forKey: "userId")
let param = ["userId":userId]
let imageData = UIImageJPEGRepresentation(profPicIV.image!, 1)
if(imageData == nil ) { return }
self.imgUploadButton.isEnabled = false
let uploadScriptUrl = URL(string: "http://xxx.xxx.xxx.xxx/scripts/imageUpload.php")
let boundary = generateBoundaryString()
var request = NSMutableURLRequest(url: uploadScriptUrl!)
request.httpMethod = "POST"
request.httpBody = createBodyWithParameters(param as! [String : String], filePathKey: "file", imageDataKey: imageData!, boundary: boundary)
request.setValue("multipart/form-data; boundary=\(boundary)", forHTTPHeaderField: "Content-Type")
if (profPicIV.image == nil)
{
return
}
if(imageData == nil)
{
return
}
let session = URLSession.shared
let task = session.dataTask(with: request as URLRequest, completionHandler: {
(
data, response, error) in
guard ((data) != nil), let _:URLResponse = response, error == nil else {
print("error")
return
}
if let dataString = NSString(data: data!, encoding: String.Encoding.utf8.rawValue)
{
print(dataString)
}
})
task.resume()
}
along with the createBodyWithParameters:
func createBodyWithParameters(_ parameters: [String: String]?, filePathKey: String?, imageDataKey: Data, boundary: String) -> Data {
let body = NSMutableData();
if parameters != nil {
for (key, value) in parameters! {
body.appendString("--\(boundary)\r\n")
body.appendString("Content-Disposition: form-data; name=\"\(key)\"\r\n\r\n")
body.appendString("\(value)\r\n")
}
}
let filename = "menu-image.jpg"
let mimetype = "image/jpg"
body.appendString("--\(boundary)\r\n")
body.appendString("Content-Disposition: form-data; name=\"\(filePathKey!)\"; filename=\"\(filename)\"\r\n")
body.appendString("Content-Type: \(mimetype)\r\n\r\n")
body.append(imageDataKey)
body.appendString("\r\n")
body.appendString("--\(boundary)--\r\n")
return body as Data
}
}
//add appendString function
extension NSMutableData {
func appendString(_ string: String) {
let data = string.data(using: String.Encoding.utf8, allowLossyConversion: false)
append(data!)
}
}
My PHP page on my webserver looks like this:
<?php
$user_id = $_POST["userId"];
$target_dir = "../profPics/" . $user_id;
if(!file_exists($target_dir))
{
mkdir($target_dir, 0744, true);
}
$target_dir = $target_dir . "/" . basename($_FILES["file"]["name"]);
if (move_uploaded_file($_FILES["file"]["tmp_name"], $target_dir)) {
echo json_encode([
"message" => "The file ". basename( $_FILES["file"]["name"]). " has been uploaded.",
"status" => "OK",
"userId" => $user_id
]);
} else {
echo json_encode([
"message" => "Sorry, there was an error uploading your picture.",
"status" => "Error",
"userId" => $user_id
]);
}
?>
but then I try to upload an image and it prints out an error in the console saying:
{"message":"Sorry, there was an error uploading your picture.","status":"Error","userId":"6"}
It is correctly grabbing the userId from my saved login info, and is successfully posting it to the PHP page because the PHP page is returning it in the error (userId = 6.) I can't see anything wrong in the apache error.log. Can anyone see where I'm going wrong? Thanks!