简体   繁体   English

PHP-如何将文件uri从移动设备上传到Web服务器?

[英]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. 但是,我的php脚本存在一些问题,当我上传屏幕截图的数据URI时,它可以正常工作,但是当我上传图像的文件URI时,上传至Web服务器的图像已损坏。 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. 我认为您使用php $ _FILES superglobals数组,最好使用php脚本将文件或图像上传到移动设备。

base64_decode()- it time consuming process to upload file to server. base64_decode()-将文件上传到服务器非常耗时。

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.";
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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