简体   繁体   中英

PHP - How to upload file uri from mobile device to web server?

I'm trying to build an mobile app that is capable to upload images to server. However, there's some problem with my php script, when I upload data URI of a screenshot, it works fine, but when I upload file URI of an image, the image uploaded into web server is broken. Can anyone help me to check what is wrong with the script?

<?php
//Generate a folder if it doesn't exist
if (!file_exists('user_images/'))
{
    mkdir('user_images', 0755, true);
}

//Get submitted data by user
if (isset($_POST['CanvasPic'])) {
    $img1 = $_POST['CanvasPic'];
} else {
    $img1 = '';
}

if (isset($_POST['name'])) {
    $name = $_POST['name'];
} else {
    $name = '';
}

define('UPLOAD_DIR', 'user_images/');

//Remove some useless string before to create image properly
//Decode base64 then generate new name
if ($img1) { 
    $img1 = str_replace('data:image/jpeg;base64,', '', $img1);
    $img1 = str_replace(' ', '+', $img1);
    $data1 = base64_decode($img1);
    $file1 = UPLOAD_DIR . $name . "_" . uniqid() . '.jpeg';
    $success = file_put_contents($file1, $data1);
}

//Output a URL where is saved.
$locator = $file1;

//Display a text, otherwise if error happened.
print $locator ? $file1 : 'Could not save the file!';
?>

I think you php $_FILES superglobals array it is better to file or image uploading using php script to mobile device.

base64_decode()- it time consuming process to upload file to server.

Try below code.

    $name = isset($_POST['name']) ? $_POST['name'] : '';
    $uploadFileName = $name."_".uniqid().".jpeg";
    define('UPLOAD_DIR', 'user_images/');
    if (move_uploaded_file($_FILES['CanvasPic']['tmp_name'],UPLOAD_DIR.$uploadFileName)) {
        echo "Uploaded.";
    } else {
        echo "File was not uploaded.";
    }

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