我正在尝试使用javascript发布html表单,但我无法找到如何作为参数传递文件。如果我不使用javascript发布表单一切正常。我的问题是我不知道如何将文件数组传递给javascript变量。我尝试了不同的方法,但我找不到正确的方法:
var fileToUpload1 = $("#fileToUpload2").val();
var fileToUpload1 = document.getElementById("fileToUpload2").files[0];
var fileToUpload1 = document.forms['imageform2']['fileToUpload2'].files[0];
我发布我的代码以防万一。 html表单和javascript都在同一个文件中。上传代码位于名为upload.php的单独文件中。
html表格:
<form id="imageform2" action="upload.php" method="post" enctype="multipart/form-data">
<p> Add new photo</p>
<p>Description :
<textarea id="description2" name= "description2" rows=6 cols=20 required></textarea></p>
Category :
<select id="category2" name="category">
<option value="0">Face</option>
<option value="1">Landscape</option>
<option value="2">Attraction</option>
<option value="3">Object</option>
</select>
<p>Select image:
<input id="fileToUpload2" type="file" name="fileToUpload2" required></p>
<input id="submit" type="button" value="Submit">
<input type="reset" value="Reset">
</form>
的javascript:
<script>
$(document).ready(function() {
$("#submit").click(function() {
var description1 = $("#description2").val();
var category1 = $("#category2").val();
var fileToUpload1 = $("#fileToUpload2").val();
alert(description1 + " " + category1 + " " + fileToUpload1);
if (description1 == '' || category1 == '')
{
if (description1 == '') alert("Insertion Failed description is Blank....!!");
else if (category1 == '') alert("Insertion Failed category is Blank....!!");
//else if (fileToUpload1 == '') alert("Insertion Failed fileToUpload is Blank....!!");
else alert("Insertion Failed Some Fields are Blank....!!");
}
else
{
// Returns successful data submission message when the entered information is stored in database.
$.post("upload.php",
{
description: description1,
category: category1,
fileToUpload: fileToUpload1
}, function(data) {
alert(data);
});
}
});
});
</script>
上传:
<?php
$target_dir = "uploads/";
$target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);
$uploadOk = 1;
$imageFileType = pathinfo($target_file,PATHINFO_EXTENSION);
// Check if image file is a actual image or fake image
session_start();
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;
}
}
// Check if file already exists
if (file_exists($target_file)) {
echo "Sorry, file already exists.";
$uploadOk = 0;
}
// Check file size
if ($_FILES["fileToUpload"]["size"] > 2000000) {
echo "Sorry, your file is too large.";
$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["fileToUpload"]["tmp_name"], $target_file)) {
//echo "The file ". basename( $_FILES["fileToUpload"]["name"]). " has been uploaded.";
$_SESSION['uploaded']="true";
} else {
echo "Sorry, there was an error uploading your file.";
}
}
?>
答案 0 :(得分:1)
使用FormData提交包含文件输入的AJAX表单。
首先,让我们注意在表单上触发的onsubmit
事件,而不是按钮上的onclick
事件。
为了使用FormData,我们需要使用$.ajax()代替$ .post(),因为有些设置需要添加才能正常工作。 FYI $ .post()是对POST请求使用$ .ajax()的简便方法。如果您需要更多配置设置,就像我们现在一样,请使用$ .ajax()。
$(document).ready(function() {
$("#imageform2").submit(function(e) {
e.preventDefault();
// simplified validation logic
if ($("#description2").val() == '') {
alert("Insertion Failed description is Blank....!!");
} else if ($("#category2").val() == '') {
alert("Insertion Failed category is Blank....!!");
} else if ($("#fileToUpload2").val() == '') {
alert("Insertion Failed fileToUpload is Blank....!!");
} else {
// send request
$.ajax({
type: this.method,
url: this.action,
data: new FormData(this), // important
processData: false, // important
contentType: false, // important
success: function (data) {
alert(data);
}
});
}
});
});
接下来在服务器端,让我们改进你的文件检查。在操作它之前,你应该总是检查是否存在超全局变量。
让我们将验证逻辑包装在try
和catch
中。如果在某一点出现错误,继续验证是没有意义的。如果通过使用适当的消息抛出异常,我们将退出验证。
// just in case, let's turn on the errors
error_reporting(E_ALL);
ini_set('display_errors', 1);
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
$file = isset($_FILES['fileToUpload2']['tmp_name']) ? $_FILES['fileToUpload2'] : null;
// start validation
try {
// check if file was NOT provided
if (!$file ||
!file_exists($file['tmp_name']) ||
!is_uploaded_file($file['tmp_name']) ||
$file['error'] !== UPLOAD_ERR_OK) {
throw new Exception('No file was given.');
}
// check if file is NOT an image
$size = getimagesize($file['tmp_name']);
if ($size === false) {
throw new Exception('File is not an image.');
}
// check if file already exists
$target_dir = 'uploads/';
$target_file = $target_dir . basename($file['name']);
if (file_exists($target_file)) {
throw new Exception('File already exists.');
}
// check file size is too large
if ($file['size'] > 2000000) {
throw new Exception('File is too large.');
}
// check file extension is NOT accepted
$extension = strtolower(pathinfo($file['name'], PATHINFO_EXTENSION));
if (!in_array($extension, ['jpg', 'png', 'gif'])) {
throw new Exception('Only JPEG, PNG & GIF files are allowed.');
}
// if it passes all checks, try uploading file
if (!move_uploaded_file($file['tmp_name'], $target_file)) {
throw new Exception('There was an error uploading your file.');
}
// if we reach this point, then everything worked out!
echo 'The file ' . basename($file['name']) . ' has been uploaded.';
} catch (Exception $e) {
echo $e->getMessage();
}
}
当然,验证可以进一步改进 - 但这只是一个简单的例子。