我目前正在处理一些文件,其中“fileA.php”有一个选项(除其他外)将图像上传到我的服务器。 “上传图片”按钮调用“upload.php”以确保它符合我所需的参数,上传图像,生成随机名称,然后将图像重命名为随机名称。
我希望能够将图片的新名称从upload.php返回到fileA.php,这样我就可以为用户提供某种弹出或消息:
“您的图片已成功上传并重命名为xyz.jpg”
我目前正在使用jQuery和PHP POST的组合在文件之间发送数据。我看过很多帖子,答案似乎是“从upload.php中回复你想要的数据然后需要fileA.php中的上传文件”,但是我无法让它工作,我理想地喜欢返回upload.php中生成的随机文件名,保存在fileA.php的变量中
我运气不好吗?谢谢你的阅读。
在我的“upload.php”文件末尾的以下代码中,我想将$ mediaPath的值返回给fileA.php
if ($uploadOk == 0) {
echo "Sorry, your file was not uploaded.";
// if everything is ok, try to upload file
} else {
if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file)) {
$randName = substr(md5(rand()), 0, 15) . '.' . $imageFileType; //generates a pseudorandom string 2^31(? I think so, also saw 2^32 somewhere, but how?) possibilities, as the md5 hash of a random int truncated to 15 characters
rename($target_file, "/var/www/html/uploads/" . $randName);
echo "The file ". basename( $_FILES["fileToUpload"]["name"]). " has been uploaded and renamed to <new name here>";
} else {
echo "Sorry, there was an error uploading your file.";
}
}
$mediaPath = "/var/www/html/uploads/" . $randName;
return $mediaPath;
然后我想我需要在“fileA.php”中实现某种jQuery函数,如下所示:
$.ajax({
type: "POST",
url: "upload.php",
datatype: "html",
data: dataString,
success: function(data) {
alert(data);
}
});
这可以获取“$ mediaPath”的值并向我发出警告 - 到目前为止,这并没有给我任何将插入到文件中的“数据”值,它只是输出通用语句硬编码到upload.php?
继续试一试,很想最终破解这个案子!对所有这些/最佳实践,欢呼的所有合理建议持开放态度。
编辑 - 尝试更新以包含Jamie M的答案:
我的jQuery:
$(document).ready(function() {
$('#imageForm').ajaxForm(function() {
$.ajax({
type: "POST",
url: "upload.php",
dataType: "json", // We want a JSON response
data: dataString, // I have to assume this is already set by the upload utility
success: function(data) {
alert(data.image); // Specify the index
}
});
});
});
</script>
我的HTML / PHP: 选择要上传的图片:
我的upload.php
header('Content-type: application/json'); // Tell the browser what to expect so it can handle it properly
$target_dir = "uploads/";
$target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);
$uploadOk = 1;
$imageFileType = strtolower(pathinfo($target_file,PATHINFO_EXTENSION));
// Grabs the file extension of the submitted file, to be used on/around line 28
if(isset($_POST["submit"])) {
$check = getimagesize($_FILES["fileToUpload"]["tmp_name"]);
if($check !== false) {
echo "File is an image - " . $check["mime"] . ".";
$uploadOk = 1;
} else {
echo "File is not an image.";
$uploadOk = 0;
}
}
// Checks uploads/ to see if file already exists, throws uploadOk to 0 therefore sending an error if it does. This is probably going to be made useless by randomizing the upload names. Also what if two people want to use the same picture?
if (file_exists($target_file)) {
echo "Sorry, file already exists. \n";
$uploadOk = 0;
}
// Check file size
if ($_FILES["fileToUpload"]["size"] > 2000000) {
echo "Sorry, your file is too large. \n";
$uploadOk = 0;
}
// Allow certain file formats, checks to make sure it is a valid image
format using $imageFileType
if($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg"
&& $imageFileType != "gif" ) {
echo "Sorry, only JPG, JPEG, PNG & GIF files are allowed. \n";
$uploadOk = 0;
}
// Check if $uploadOk is set to 0 by an error
if ($uploadOk == 0) {
echo "Sorry, your file was not uploaded. \n";
// if everything is ok, try to upload file
} else {
if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"],
$target_file)) {
$randName = substr(md5(rand()), 0, 15) . '.' . $imageFileType;
//generates a pseudorandom string 2^31(? I think so, also saw 2^32 somewhere, but how?) possibilities, as the md5 hash of a random int truncated to 15 characters
rename($target_file, "/var/www/html/uploads/" . $randName);
$data = ['image' => $randName]; // You can add as many items as you like here
echo "The file ". basename( $_FILES["fileToUpload"]["name"]). " has been uploaded and renamed to <new name here>";
} else {
echo json_encode($data);
}
}
echo json_encode($data); // Encode it properly to ensure the response is valid for browser parsing
?>
到目前为止,我没有成功,上面的代码(貌似)没有从upload.php返回任何值,并且控制台中没有可见的错误。
答案 0 :(得分:3)
我希望我能正确理解你的问题。
这里还需要几个步骤。首先,您需要以可预测的方式专门返回JSON数据。为此,我在upload.php中建议以下内容:
$data = ['image' => $mediaPath]; // You can add as many items as you like here
header('Content-type: application/json'); // Tell the browser what to expect so it can handle it properly
echo json_encode($data); // Encode it properly to ensure the response is valid for browser parsing
exit(); // Optional, but nothing beyond this point can be properly returned.
JSON期望数据被回显,而不是返回,并且通过在数组中建立索引,它可以在下一步(fileA.php)中轻松访问:
<script type="text/javascript">
$.ajax({
type: "POST",
url: "upload.php",
dataType: "json", // We want a JSON response
data: dataString, // I have to assume this is already set by the upload utility
success: function(data) {
alert(data.image); // Specify the index
}
});
</script>
这应该可行,然后您只需要使用data.image进行操作。
修改
您编辑的处理代码中存在许多缺陷,我(很快,并非完美)试图在下面解决一些问题。有一点不清楚的是你的上传工具在成功处理的情况下期望看到的内容 - 可能是你正在生成的响应正在破坏它。
无论如何,请尝试以下方法:
<?php
$target_dir = "uploads/";
$target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);
$uploadOk = true;
$imageFileType = strtolower(pathinfo($target_file,PATHINFO_EXTENSION));
$errorMsgs = array();
// Grabs the file extension of the submitted file, to be used later
if(isset($_POST["submit"])) {
$check = getimagesize($_FILES["fileToUpload"]["tmp_name"]);
if($check === false) {
$errMsgs[] = "File is not an image.";
$uploadOk = false;
}
} else {
// What are we doing here?
}
// Checks uploads/ to see if file already exists, throws uploadOk to 0 therefore sending an error if it does. This is probably going to be made useless by randomizing the upload names. Also what if two people want to use the same picture?
if (file_exists($target_file)) {
// NOTE: we don't echo yet as this would break any subsequent output
$errMsgs[] = "Sorry, file already exists. \n";
$uploadOk = false;
}
// Check file size
if ($_FILES["fileToUpload"]["size"] > 2000000) {
$$errMsgs[] = "Sorry, your file is too large. \n";
$uploadOk = false;
}
// Allow certain file formats, checks to make sure it is a valid image format using $imageFileType
if($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg"
&& $imageFileType != "gif" ) {
$$errMsgs[] = "Sorry, only JPG, JPEG, PNG & GIF files are allowed. \n";
$uploadOk = false;
}
// Check if $uploadOk has been negated
if (!$uploadOk) {
// Set header for browser to understand
header('Content-type: application/json');
echo implode(', ', $errMsgs);
exit();
} else {
if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file)) {
$randName = substr(md5(rand()), 0, 15) . '.' . $imageFileType;
//generates a pseudorandom string 2^31(? I think so, also saw 2^32 somewhere, but how?) possibilities, as the md5 hash of a random int truncated to 15 characters
rename($target_file, "/var/www/html/uploads/" . $randName); // What if this fails?
$data = array(
'success' => 1,
'image' => $randName,
'message' => "The file " . basename( $_FILES["fileToUpload"]["name"]) . " has been uploaded and renamed to {$randName}"
);
// You can add as many items as you like above. NOTE you can now use data.image for the image name or data.message for the full string.
// NOTE: What is the uploader expecting to receive in case of success?
header('Content-type: application/json');
echo json_encode($data); // This was probably your main issue
} else {
header('Content-type: application/json');
echo "Unable to store file in system";
}
}
?>