2012-06-29 71 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/ –