duandeng2011 2015-07-29 17:13
浏览 31
已采纳

将图像URL上载到mySQL数据库以获取JSON输出

So I need to upload images and their URLs to a mySQL database. Right now I have it working so that an image and its relative path is being uploaded to the database and I am outputting it to JSON like so: (filepath is the relative path)

[{"name":"photo","image":"savedphoto.jpg","filepath":"uploads/savedphoto.jpg"}]

What I want is the full URL like so:

[{"name":"photo","image":"savedphoto.jpg","filepath":"http://mywebsite.com/uploads/savedphoto.jpg"}]

Here is the code I have:

$name = $_POST['new'];
$target_dir = "uploads/";
$uploadOk = 1;
$target_file = $target_dir . basename($_FILES["image"]["name"]);
$image_name =  addslashes($_FILES['image']['name']);

// Check if image file is a actual image or fake image
if(isset($_POST["submit"])) {
    $check = getimagesize($_FILES["fileToUpload"]["tmp_name"]);
    if($check !== false) {
        echo "File is an image - " . $check["mime"] . ".";
        $uploadOk = 1;
    } else {
        echo "File is not an image.";
        $uploadOk = 0;
    }

    $query = mysql_query("INSERT INTO new (name, filepath, image)
        VALUES ('$name', '$target_file', '$image_name')");

    if($query)
    {
       echo"Successful";
    } else {
        echo"Error";
    }
}

Is it possible to save the full URL to the database? How would I alter the code? I want to output the data to JSON.

My JSON output file:

if ($result = mysqli_query($con, $sql))
{
$resultArray = array();
$tempArray = array();

while($row = $result->fetch_object())
{
    $tempArray = $row;
    array_push($resultArray, $tempArray);
}
echo json_encode($resultArray);
}
function_exists('json_encode');
  • 写回答

1条回答 默认 最新

  • dongpao1921 2015-07-29 17:18
    关注

    u can replace

    $query = mysql_query("INSERT INTO new (name, filepath, image)
            VALUES ('$name', '$target_file', '$image_name')");
    

    with

    $query = mysql_query("INSERT INTO new (name, filepath, image)
                VALUES ('{$name}', 'http://mywebsite.com/{$target_file}', '{$image_name}')");
    

    BUT. its better to replace in you output file

    $tempArray = $row;
    array_push($resultArray, $tempArray);
    

    with

    $tempArray = $row;
    $tempArray->filepath = "http://{$_SERVER['HTTP_HOST']}/{$tempArray->filepath}";
    array_push($resultArray, $tempArray);
    

    after that your script will work on any host properly without changing data in database

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 HFSS设计小型化180度耦合器
  • ¥15 使用CInternetSession,CHttpFile读取网页文件时有些电脑上会卡住怎么办?
  • ¥15 水下机器人的半物理仿真研究
  • ¥15 微服务假死,一段时间后自动恢复,如何排查处理
  • ¥50 webrtc-streamer TCP rtsp
  • ¥15 cplex运行后参数报错是为什么
  • ¥15 之前不小心删了pycharm的文件,后面重新安装之后软件打不开了
  • ¥15 vue3获取动态宽度,刷新后动态宽度值为0
  • ¥15 升腾威讯云桌面V2.0.0摄像头问题
  • ¥15 关于Python的会计设计