我正在开发一个应用程序,前端使用 HTML 和 js,后端使用 PHP。我有以下代码,其功能如下: 1,当点击背景图片时,用户可以选择手机中的照片作为新的背景图片,并使用PHP将图像保存在服务器上并获取图像路径,存储将路径写入数据库,然后使用 JSON 将新路径发送回前面,并将所选图像显示为新的背景图像。感谢您的帮助。
用于发送和检索数据的 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");
}
}
}
调用 JavaScript 的 HTML 代码:
<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"];
}
}
?>
最佳答案
您应该使用一些库(例如 uploadify)来上传文件而无需发布表单。
<强> DEMO
关于javascript - 如何使用Ajax将图像存储到文件夹并存储数据库路径?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26595631/