简体   繁体   中英

Upload image to Database from Swift through Php

I'm trying to upload an image to my localhost Sever and saving the path to a database. I already have some other code, where I upload a new Object. Is it possible to upload the image in the same function as shown below. I have not found any good tutorials on how to do this with other uploads in the same function (in the same sql request). The Spot object has an element image, which is the UIImage , that has to be uploaded.

The Swift code:

if let url = URL(string: "http://localhost:8080/add.php") {
    var request = URLRequest(url: url)
    request.httpMethod = "POST"
    request.timeoutInterval = 20.0
    var dataString = "secretWord=235ghzjg35" // starting POST string with a secretWord
    
    dataString = dataString + "&name=\(spot.name!)"
    dataString = dataString + "&lat=\(spot.lat!)"
    dataString = dataString + "&long=\(spot.long!)"
    
    let dataD = dataString.data(using: .utf8)
    
    do{
        let uploadJob = URLSession.shared.uploadTask(with: request, from: dataD) { data, response, error in
            if error != nil {
                DispatchQueue.main.async {
                    print("No connection")
                }
            }
            else {
                if let unwrappedData = data {
                    let returnedData = NSString(data: unwrappedData, encoding: String.Encoding.utf8.rawValue)
                    if returnedData == "1"{
                        DispatchQueue.main.async {
                            print("Upload completed")
                        }
                    }
                    else {
                        DispatchQueue.main.async {
                            print(returnedData ?? "no data back'")
                        }
                    }
                }
            }
        }
        uploadJob.resume()
    }
}

The Php code:

<?php
$secret = $_POST["secretWord"];
if ("235ghzjg35" != $secret) exit;

$name = $_POST["name"];
$lat = $_POST["lat"];
$long = $_POST["long"];

//$img0 = $_FILES['img0'];
//$target0 = "spotImages/" . $name;
//$target0 = $target0 . basename($img0);

// Create connection
$con=mysqli_connect("localhost", "user", "pass", "db");

// Check connection
if (mysqli_connect_errno()) {
    echo "Failed to connect to MySQL: " . mysqli_connect_error();
}

//then adding here the image
$sql = "INSERT INTO `table` (`id`, `name`,  `long`, `lat`) VALUES (NULL, '". $name ."', '". $long ."', '". $lat  ."');";

$result = mysqli_query($con, $sql);
echo $result;
mysqli_close($con);?>

Furthermore I wanted to know if there are any better solutions on how to manage a Database with Swift for my App. I have read some things about Firebase and Realm.io. Has anyone had any experiences? And if so, what are the pros and cons? Should I consider using that instead of my approach?

A couple of observations:

  1. The code in your question is building a application/x-www-form-urlencoded request. To upload an image, you generally would not use this type of request. The problem is that you can't include binary image data in it. You could, theoretically, base64-encode the image data when building the request and base64-decode it on the server, but that's going to make the request 33% bigger and adds unnecessary work on both client and server side.

  2. Also, if you use application/x-www-form-urlencoded , you have to percent-escape your values you send to your server (eg, if your “name” had spaces or other reserved characters in it, the request would be malformed if not percent-escaped). See HTTP Request in Swift with POST method .

  3. All that having been said, when sending images, you'd generally use multipart/form-data as outlined in Upload image with parameters in Swift , eliminating the above concerns. You can send the image and these fields in a single request.

    While I've tried to show how one would build multipart/form-data requests in that other answer, you might consider using libraries like Alamofire get you out of the weeds of building these complicated requests.

  4. When parsing the multipart/form-data request in PHP, you'd use $_FILES as outlined in Handling File Uploads .

  5. You should never just take the fields from a request and build a SQL statement from them. At worst, it leaves you susceptible to SQL injection attacks. At best, it will just fail if a user sends a string that, for example, contains the SQL string delimiter character.

    You should either bind the values to ? placeholders in your SQL using mysqli_stmt::bind_param or, if building the SQL manually, make sure to use mysqli::real_escape_string before inserting them into your SQL statement.

  6. You asked:

    Furthermore I wanted to know if there are any better solutions on how to manage a Database with Swift for my App. I have read some things about Firebase and Realm.io. Has anyone had any experiences? And if so, what are the pros and cons? Should I consider using that instead of my approach?

    This is probably too broad of a question to reasonably answer here, but in short, sure, if you want to get out of the world of writing your own server code, then, yes, you should consider those solutions. These get you out of the weeds of backend development. Re Firebase vs Realm.io, that's a matter of opinion and, as such, is considered off topic for Stack Overflow. But both are mature solutions which, as your app scales, involve some costs.

    For what it's worth, if you decide you want to write your own PHP code, I might advise considering a PHP framework, such as Laravel . It offers scaffolding for authentication, abstraction away from SQL statements, etc.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM