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.

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

报告相同问题?