gpt4 book ai didi

javascript - 如何使用 javascript 发布包含文件类型参数的表单

转载 作者:行者123 更新时间:2023-12-03 06:42:55 25 4
gpt4 key购买 nike

我正在尝试使用 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.";
}
}
?>

最佳答案

使用FormData使用包含文件输入的 AJAX 提交表单。

首先,让我们观察表单上触发的 onsubmit 事件,而不是按钮上的 onclick 事件。

为了使用FormData,我们需要使用$.ajax()相反 $.post() 因为需要添加一些设置才能使其工作。仅供引用 $.post() 是使用 $.ajax() 进行 POST 请求的简写方式。如果您需要更多配置设置(就像我们现在所做的那样),请使用 $.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);
}
});
}
});
});

接下来在服务器端,让我们稍微改进一下文件检查。在操作超全局变量之前,您应该始终检查它是否存在。

让我们将验证逻辑包装在 trycatch 中。如果在某个点出现错误,则继续验证是没有意义的。如果发生错误,我们将通过抛出带有适当消息的异常来退出验证。

// 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();
}
}

当然,验证还可以进一步改进——但这只是一个简单的例子。

关于javascript - 如何使用 javascript 发布包含文件类型参数的表单,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37871875/

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