2012-06-29 70 views
2

下面的代码允许我上传图片(使用html表单)到我的服务器上的目录。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)) 
    { 
     echo "The file ". basename($_FILES['uploadedfile']['name']). " has been uploaded"; 
    } 
    else 
    { 
     echo "Sorry, there was a problem uploading your file."; 
    } 
?> 

有什么办法可以修改它,以便它将图片添加到html页面吗?

感谢

+0

选择文本,然后按Ctrl + K to **将整个文本块缩进四个空格**以使其成为代码块。每条线周围的个人背部蜱使其无法读取! – deceze

回答

4

您上传好了后,你可以使用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 
    $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> 
+0

我想要一个允许用户上传图片的scrpit,它会自动将图片放在页面上。如果有图片会将新图片添加到页面 – Ross

+0

您可以使用uploadify http://www.uploadify.com/demos/并且一旦上传,您可以将其显示到html页面 –

+0

我希望它可以帮助,虽然Rakesh Shetty的解决方案可能会更快,更易于理解 – Indra

0

假设你有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' />"); 

}); 

希望这有助于:-)

+0

将图像添加到dom应在成功响应后进行回调。就目前而言,这是行不通的。 http://api.jquery.com/jQuery.ajax/ –