dpblwmh5218 2018-01-24 11:07
浏览 27
已采纳

如何将上传的图像显示到相应的帖子?

Working on a website where you can add news, that data gets sent to a database and then converted to json, later used in an app. I want to add a feature where when you are creating news, you can attach an image to the news. How do I display the image with the corresponding post? Not just a random uploaded image but the one you chose when you were creating the news.

My idea: My idea is to use the following W3 php scrip to upload the images:

<?php
$target_dir = "uploads/";
$target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);
$uploadOk = 1;
$imageFileType = strtolower(pathinfo($target_file,PATHINFO_EXTENSION));
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;
    }
}

but modify it so that when you create a news, it will get the news id from the database, make a new folder in /uploads/ setting the name as the id from the news, upload the images to that folder, and then when I want to display the image/s I can get the id of the news I'm viewing and display the images from that folder that corresponds to the id of the news.

That is the only Idea I can come up with and it doesn't seem the greatest. Is this the best way or is there a better way? Thanks

  • 写回答

1条回答 默认 最新

  • duanlou7910 2018-01-24 11:27
    关注

    My simple solution, to not get cluttered with folders and such, is that when you upload the image, you should rename it to include something random, like a random number along with the original name, to avoid overwriting existing files when a duplicate name is used.

    Then, in the proccess of uploading, get that newly generated name, and store it in a variable. After the image upload has finished, you could pass that parameter (the filename) in your database, and associate it with the newspost's ID.

    You will then have to simply get the filename and use it to present the image in the news post, along with its content and whatever else you have stored and associated with the news post and its ID.

    Not many folders should be used, one is more than enough. Perhaps you could create a new folder for each month and store that month's images in that folder.

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

报告相同问题?

悬赏问题

  • ¥50 求解vmware的网络模式问题 别拿AI回答
  • ¥24 EFS加密后,在同一台电脑解密出错,证书界面找不到对应指纹的证书,未备份证书,求在原电脑解密的方法,可行即采纳
  • ¥15 springboot 3.0 实现Security 6.x版本集成
  • ¥15 PHP-8.1 镜像无法用dockerfile里的CMD命令启动 只能进入容器启动,如何解决?(操作系统-ubuntu)
  • ¥30 请帮我解决一下下面六个代码
  • ¥15 关于资源监视工具的e-care有知道的嘛
  • ¥35 MIMO天线稀疏阵列排布问题
  • ¥60 用visual studio编写程序,利用间接平差求解水准网
  • ¥15 Llama如何调用shell或者Python
  • ¥20 谁能帮我挨个解读这个php语言编的代码什么意思?