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

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

报告相同问题?

悬赏问题

  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度