【发布时间】:2016-12-14 14:30:40
【问题描述】:
我正在尝试从 PC/移动设备中选择一张图片,然后单击一键将其上传到服务器,但由于某种原因,我无法获取所选图片的值(名称) - PHP 页面内的 $_FILES["pictureCapture"]["name"]。我可以使用两个按钮轻松完成此操作,一个用于浏览我设备上的图像,第二个用于上传,但这两个过程我真的需要单击一个按钮。
我的源代码:
HTML
<form action="" method="post" enctype="multipart/form-data" onsubmit="test3()">
Select image to upload:
<input type="file" name="pictureCapture" id="pictureCapture" accept="image/*; capture=camera" style="visibility:hidden;" onchange="test2();"/>
<button type="button" id="uploadPhotoFromCamera" onclick="test();">Choose an image</button>
<input id="uploadPhotoToServer" type="submit" value="Upload Image" name="submit" style="visibility:hidden;"/>
</form>
jQuery + AJAX
function test(){
event.preventDefault();
$("#pictureCapture").trigger("click");
}
function test2(){
$("#uploadPhotoToServer").trigger("click");
}
function test3(){
event.preventDefault();
var formData = new FormData();
var fileInput = document.getElementById('pictureCapture');
formData.append(fileInput.files[0].name, fileInput.files[0]);
$.ajax({
url : "upload.php", // Url to which the request is send
type : "POST", // Type of request to be send, called as method
data: formData, // Data sent to server, a set of key/value pairs (i.e. form fields and values)
cache : false, // To unable request pages to be cached
processData : false, // To send DOMDocument or non processed data file it is set to false
contentType: 'multipart/form-data',
success : function(result) // A function to be called if request succeeds
{
alert(result);
}
});
}
PHP
$target_dir = "uploads/";
$target_file = $target_dir .date('d-m-Y-H-i-s').'-'. basename($_FILES["pictureCapture"]["name"]);
$uploadOk = 1;
$imageFileType = pathinfo($target_file,PATHINFO_EXTENSION);
// Check if image file is a actual image or fake image
if(isset($_POST["submit"])) {
$check = getimagesize($_FILES["pictureCapture"]["tmp_name"]);
if($check !== false) {
echo "File is an image - " . $check["mime"] . ".";
$uploadOk = 1;
} else {
echo "File is not an image.";
$uploadOk = 0;
}
}
// Allow certain file formats
if($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg" && $imageFileType != "gif" ) {
echo "Sorry, only JPG, JPEG, PNG & GIF files are allowed.";
$uploadOk = 0;
}
// Check if $uploadOk is set to 0 by an error
if ($uploadOk == 0) {
echo "Sorry, your file was not uploaded.";
// if everything is ok, try to upload file
} else {
if (move_uploaded_file($_FILES["pictureCapture"]["tmp_name"], $target_file)) {
echo "The file ". basename( $_FILES["pictureCapture"]["name"]). " has been uploaded.";
} else {
echo "Sorry, there was an error uploading your file.";
}
}
请你帮我解决这个问题!
【问题讨论】:
-
也许用 test2 来触发表单提交?
-
@dimis283,我知道它会按照您建议的方式工作,但我需要使用 AJAX 才能在我的 html 页面中显示错误或成功消息
-
我的意思是这样的 airpair.com/js/jquery-ajax-post-tutorial 查看 2 AJAX POST 示例,jQuery 方式
-
附注 - 不要使用
getimagesize来检查文件是否是有效的图像文件。 php.net/manual/en/…