我正在開發一個應用程序,前端使用HTML和js,後端使用PHP。我有以下代碼應該有這樣的功能:1,當點擊背景圖片時,用戶可以從那裏選擇手機照片作爲新的背景圖片,並使用PHP將圖片保存到服務器上並獲取圖片路徑,存儲路徑導入數據庫,然後使用JSON將新路徑重新發送到前端,並將所選圖像顯示爲新的背景圖像。謝謝你的幫助。如何將圖像存儲到文件夾並使用Ajax存儲數據庫的路徑?
JavaScript來發送和檢索數據:
function UploadImageDialog()
{
$("#newProfileImage").click();
}
function profileImageSelected(fileInput)
{
var xhr = new XMLHttpRequest();
xhr.open("POST", "UploadProfileImage.php", true);
var formData = new FormData();
formData.append("file", fileInput.files[0]);
xhr.send(formData);
xhr.onload = function() {
alert(xhr.responseText); //test the returned info from PHP.
if(xhr.responseText != ""){
$("#profileBackgroundImage").setAttribute("src", xhr.responseText);
}
else
{
alert("Your file failed to upload");
}
}
}
HTML代碼來調用JavaScript:
<div style="width:91.5vw;height:78.5vh;margin-top:10.5vh;">
<img class="backgroundImage" id="pictureSrc" src="img/Jenny.jpg" onclick="UploadImageDialog()" />
</div>
<input type="file" id="newProfileImage" style="display:none;" onchange="profileImageSelected(this)"/>
PHP代碼來獲取路徑:
<?php
if(is_uploaded_file($_FILES['file']['tmp_name'])) // if user uploads file
{
if (!file_exists("./img/EventImages/" . $_FILES["file"]["name"]))
{
if (move_uploaded_file($_FILES["file"]["tmp_name"], "./img/EventImages/" . $_FILES["file"]["name"]))
{
echo "img/EventImages/" . $_FILES["file"]["name"];
}
}
else
{
echo "img/EventImages/" . $_FILES["file"]["name"];
}
}
?>
可能值得看看http://stackoverflow.com/questions/450876/upload-image-to-server-using-php-store-file-name-in-a-mysql-database-with-othe – Vector 2014-10-27 19:51:02
有什麼問題?什麼不行? – Rudie 2014-10-27 20:06:09
也許有幫助:http://js1.hotblocks.nl/tests/ajax/file-drag-drop.html – Rudie 2014-10-27 20:08:37