简体   繁体   English

Jquery & Ajax -> 无法上传文件

[英]Jquery & Ajax -> File upload not possible

I got totally lost.我完全迷路了。

Ive tried to make some Image Upload function in PHP and everything works fine.我尝试在 PHP 中制作一些图像上传功能,一切正常。 Because i dont want the whole Page to reload, when uploading a File i wanted to use AJAX with Jquery, to send the Form Content (Image) via POST to a file like upload.php with an hidden ajax request.因为我不希望整个页面重新加载,所以在上传文件时我想将 AJAX 与 Jquery 一起使用,通过 POST 将表单内容(图像)发送到带有隐藏 ajax 请求的 upload.php 之类的文件。

No matter what i try its impossible to send anything with formData().无论我尝试什么都不可能用 formData() 发送任何东西。 I copied & pasted several Sample Codes, tried changing the Code, nothing happens when i use formData().我复制并粘贴了几个示例代码,尝试更改代码,当我使用 formData() 时没有任何反应。

A normal request with Jquery / Ajax, using POST works fine. Jquery/Ajax 的正常请求,使用 POST 工作正常。

Here ist the Sample of my last used Code..这是我上次使用的代码示例..

Could my XamPP has been misconfigured, or what could cause that really not one of the Scripts from google, tutorial pages etc works?是不是我的 XamPP 配置错误,或者是什么原因导致 google、教程页面等中的脚本中的一个不起作用?

 <!DOCTYPE html> <html> <body> <script type="text/javascript" src="jquery.min.js"></script> <form id="Test" action="" method="post" enctype="multipart/form-data"> Select image to upload: <input type="file" name="fileToUpload" id="fileToUpload"> </form> <button id="Knopf">Knopf</button> <div id="Disp">fghfgh</div> </body> <script> $(document).ready(function(){ $("#Knopf").click(function(){ var formData = new FormData(Test); $.ajax({ url : "uploadtest2.php", type : "POST", data : formData, cache : false, contentType : false, processType : false, success : function() { $("#Disp").html(result); } }); }); }); </script> </html>

 <?php $target_dir = "Media/uploads/"; $target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]); $uploadOk = 1; $imageFileType = strtolower(pathinfo($target_file,PATHINFO_EXTENSION)); // Check if image file is a actual image or fake image 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"] > 500000) { 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 ". htmlspecialchars( basename( $_FILES["fileToUpload"]["name"])). " has been uploaded."; } else { echo "Sorry, there was an error uploading your file."; } } ?>

The problem is this:问题是这样的:

if(isset($_POST["submit"])) {

There's no element named submit in the form, so this check fails.表单中没有名为submit的元素,因此此检查失败。 Even if you had a submit button in the form, it wouldn't be included in formData , because buttons are only automatically included in POST data when they trigger normal form submission.即使表单中有提交按钮,它也不会包含在formData ,因为按钮仅在触发正常表单提交时才会自动包含在 POST 数据中。

You can add that to formData .您可以将其添加到formData

var formData = new FormData(Test);
formData.set("submit", "1");

Or you could change your test to或者你可以改变你的测试

if ($_SERVER['REQUEST_METHOD'] == 'POST') {

Please see: https://developer.mozilla.org/en-US/docs/Web/API/FormData/FormData请参阅: https : //developer.mozilla.org/en-US/docs/Web/API/FormData/FormData

You must use a Form Element:您必须使用表单元素:

An HTML <form> element — when specified, the FormData object will be populated with the form's current keys/values using the name property of each element for the keys and their submitted value for the values.一个 HTML <form>元素——当指定时, FormData对象将使用表单的当前键/值填充,使用每个元素的名称属性作为键及其提交的值。 It will also encode file input content.它还将对文件输入内容进行编码。

Consider the following example.考虑以下示例。

 $(function() { $("#Test").submit(function(e) { e.preventDefault(); var formData = new FormData(this); $.ajax({ url: "uploadtest2.php", type: "POST", data: formData, cache: false, contentType: false, processType: false, success: function(result) { $("#Disp").html(result); } }); }); $("#Knopf").click(function() { $("#Test").submit(); }); });
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <form id="Test" action="" method="post" enctype="multipart/form-data"> Select image to upload: <input type="file" name="fileToUpload" id="fileToUpload" /> </form> <button id="Knopf" type="submit">Knopf</button> <div id="Disp">fghfgh</div>

It is better to bind to the submit callback.最好绑定到submit回调。 This way, if the User submits the form or clicks Submit, the callback is triggered.这样,如果用户提交表单或点击提交,就会触发回调。 We need to .preventDefault() on the Event to ensure the Form doesn't post or submit the data.我们需要在事件上使用.preventDefault()以确保表单不会发布或提交数据。 Now we can then perform the AJAX call without the page being refreshed.现在我们可以在不刷新页面的情况下执行 AJAX 调用。

In your success callback, you must pass in a variable to be used for the returned data.在您的success回调中,您必须传入一个用于返回数据的变量。 Otherwise result will be undefined.否则result将是未定义的。

With the proper FormData, there should be no issue uploading.使用正确的 FormData,上传应该没有问题。 this in the callback refers to the Form Element itself.回调中的this指的是表单元素本身。

Consider updating your PHP as well:考虑更新您的 PHP:

if(isset($_POST["submit"])) {

Change this to:将此更改为:

if(isset($_POST["fileToUpload"])) {

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM