PHP - 上传图片并在页面上显示

3
以下代码允许我使用HTML表单将图片上传到服务器上的一个目录。
<?php 

    $target = "http://www.mockcourt.org.uk/user/htdocs/pics/2012/";
    $target = $target . basename( $_FILES['uploaded']['name']); 
    $ok=1; 

    if (move_uploaded_file($_FILES['uploaded']['tmp_name'], $target)) 
    {
        echo "The file ". basename( $_FILES['uploadedfile']['name']). " has been uploaded";
    } 
    else
    {
        echo "Sorry, there was a problem uploading your file.";
    }
?>

有没有办法修改它,使其将图片添加到HTML页面中呢?谢谢。

选择您的文本,然后按Ctrl+K将整个文本块缩进四个空格,使其成为代码块。每行周围的反引号会使其难以阅读! - deceze
2个回答

5

上传完成后,您可以使用JavaScript将其放置在HTML页面上。

不过我不太确定您的问题是什么。

编辑:

因此,在您的页面上有一个HTML表单:

<form action="imageUpload.php" method="post" enctype="multipart/form-data" target="upload_target"  onsubmit="jupload();"  id="form1" >
    <div style="visibility:'hidden';" class="imageholder"> <!-- a gif image to show that the process wasn't finished -->
    </div>
    <input type="file" name="imgfile" /> 
    <input type="submit" name="uploadButton" class="upbtn" value="Submit" />
</form>

Javascript(JQUERY) 上传和添加图片的代码:

function jupload()
{
    $(".imageholder").append('<img src="./images/loading.gif">');
}

function juploadstop(result)
{
    if(result==0)
    {
        $(".imageholder").html("");

    }
    // the result will be the path to the image
    else if(result!=0)
    {
        $(".imageholder").html("");
        // imageplace is the class of the div where you want to add the image  
        $(".imageplace").append("<img src='"+result+"'>");
    }   
}

PHP 代码:

<?php
    $target = "http://www.mockcourt.org.uk/user/htdocs/pics/2012/";
    $target = $target . basename( $_FILES['uploaded']['name']) ; 
    $ok=1; 

    if (move_uploaded_file($_FILES['uploaded']['tmp_name'], $target)) 
    {
        $result=$target;
    } 
    else
    {
        $result=0;
    }
?>

<script language="javascript" type="text/javascript">
    window.top.window.juploadstop(<?php echo $result; ?>);
</script>

我想要一个脚本,让用户上传图片并自动将其放置在页面上。如果页面上已有图片,则会将新图片添加到该页面上。 - Ross
你可以使用 Uploadify http://www.uploadify.com/demos/ 进行上传,上传完成后可以在 HTML 页面中显示。 - Rakesh Shetty
我希望这有所帮助,不过Rakesh Shetty的解决方案可能更快更容易理解。 - Indra

1
假设您有一个HTML表单来提交图像...将提交按钮制作成不是提交按钮,而只是一个按钮...例如:
<input type='button' id='submit_form' value='upload' />

在 JavaScript 中,使用 Ajax 提交表单,并使用 Jquery 在网页中显示它。
$('#submit_form')click(function(){
  $.ajax({
    type: 'POST',
    url: path/phpfile.php,
    data: image_input_name
  });

//after submitting, get the url of the image form the server

  $('#div_to_display_image').html("<img src='path/image_file.jpg' alt='this' />");

});

希望这可以帮到你 :-)

将图像添加到DOM应在成功响应后的回调函数中进行。目前这样做是行不通的。http://api.jquery.com/jQuery.ajax/ - Ryan Ore

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接