gpt4 book ai didi

php - ajax图片上传和预览表单

转载 作者:行者123 更新时间:2023-11-29 13:45:43 25 4
gpt4 key购买 nike

我正在使用脚本输出上传的图像预览。效果很好。我只是想在一个 div 中显示图像,并在另一个 div 中显示错误或成功按摩。有机会这样做吗?这是代码。

Java 脚本

<script type="text/javascript">
$(document).ready(function(){
$('#photoimg').live('change', function(){
$("#preview").html('');
$("#preview").html('<img src="loader.gif" alt="Uploading...."/>');
$("#imageform").ajaxForm(
{
target: '#preview'
}).submit();
});
});
</script>

HTML 代码

<?php
include('db.php');
session_start();
$session_id='1'; // User login session value
?>

<div id="output"></div>

<form id="imageform" method="post" enctype="multipart/form-data" action='ajaximage.php'>
Upload image <input type="file" name="photoimg" id="photoimg" />
</form>

<div id='preview'>
</div>

PHP 代码

include('db.php');
session_start();
$session_id='1'; // User session id
$path = "uploads/";

$valid_formats = array("jpg", "png", "gif", "bmp","jpeg");
if(isset($_POST) and $_SERVER['REQUEST_METHOD'] == "POST")
{
$name = $_FILES['photoimg']['name'];
$size = $_FILES['photoimg']['size'];
if(strlen($name))
{
list($txt, $ext) = explode(".", $name);
if(in_array($ext,$valid_formats))
{
if($size<(1024*1024)) // Image size max 1 MB
{
$actual_image_name = time().$session_id.".".$ext;
$tmp = $_FILES['photoimg']['tmp_name'];
if(move_uploaded_file($tmp, $path.$actual_image_name))
{
mysql_query("UPDATE users SET profile_image='$actual_image_name' WHERE uid='$session_id'");
echo "<img src='uploads/".$actual_image_name."' class='preview'>";

echo "<span class=ok-msg">Image has been uploaded..!</span>";
}
else
echo "<span class=error-msg">failed<span>";
}
else
echo "<span class=error-msg">Image file size max 1 MB</span>";
}
else
echo "<span class=error-msg">Invalid file format..</span>";
}
else
echo "<span class=error-msg">Please select image..!</span>";
exit;
}

我喜欢在同一位置的 div 预览中显示所有消息(错误消息、正常消息)并在 div 输出和图像中显示。谁能告诉我该怎么做。提前致谢。

最佳答案

使用json dataType成功回调函数,例如,

$("#imageform").ajaxForm(
{
dataType:'json',
success:function(json){
$('#output').html(json.img);
$('#preview').html(json.msg);
}
}).submit();

PHP

返回数据,例如

echo json_encode(array('img'=>"<img src='...' />",'msg'=>"Message goes here"));
return;

关于php - ajax图片上传和预览表单,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17442514/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com