图像未使用 ajax 发布(未提交表单)


Image not getting posted with ajax(without submitting the form)

我的形式是 -

<form id="fileupload" method="post" enctype="multipart/form-data">
     <input type="file" id="headerimage" spellcheck="true" class="typography" name="headerimage">
</form>

我的 ajax 代码是 -

var fileData = new FormData($('#fileupload'));
            fileData.append('imagefile', $('#headerimage')[0].files);
            $.ajax({
                    type    : 'post',
                    data    : fileData,
                    url     : 'UploadImage.php',
                    dataType: 'json',
                    processData: false,
                    success : function(data)
                    {
                        alert("done");
                    },
                });

Php 代码 -

<?php
    # Data Base Connection
    require_once('conn/dbConn.php');
    var_dump($_REQUEST);
    if (!empty($_FILES)) {
        var_dump($_FILES);
    }

请帮忙。在 php 页面上,我没有获取文件数据。

HTML 代码:

<form id="fileupload" method="post" enctype="multipart/form-data">
<input name="userImage" id="uploadForm" type="file" class="inputFile" />
</form>

阿贾克斯 :

<script type="text/javascript">
$(document).ready(function (e){
$("#fileupload").on('submit',(function(e){
e.preventDefault();
$.ajax({
url: "UploadImage.php",
type: "POST",
data:  new FormData(this),
contentType: false,
cache: false,
processData:false,
success: function(data){
$("#targetLayer").html(data);
},
error: function(){}             
});
}));
});
</script>

使用此 JavaScript

$(document).on("submit", "#fileupload", function(event)
{
    event.preventDefault();        
    $.ajax({
        url: 'UploadImage.php',
        type: 'POST',            
        data: new FormData(this),
        dataType: 'json',
        processData: false,
        contentType: false,
        success: function (data, status)
        {
        }
    });        
});

试试这个...

图片将上传,无需提交表格

<form id="uploadimage" action="" method="post" enctype="multipart/form-data">
<div id="image_preview"><img id="previewing" src="noimage.png" /></div>
<hr id="line">
<div id="selectImage">
<label>Select Your Image</label><br/>
<input type="file" name="file" id="file" required />  
</div>
</form>
<script>
$(document).ready(function (e) {
$("#uploadimage").on('change',(function(e) {
e.preventDefault();
$.ajax({
url: "UploadImage.php", // Url to which the request is send
type: "POST",             // Type of request to be send, called as method
data: new FormData(this), // Data sent to server, a set of key/value pairs (i.e. form fields and values)
contentType: false,       // The content type used when sending data to the server.
cache: false,             // To unable request pages to be cached
processData:false,        // To send DOMDocument or non processed data file it is set to false
success: function(data)   // A function to be called if request succeeds
{
}
});
}));
});
</script>

上传图片.php

<?php
if(isset($_FILES["file"]["type"]))
{
$validextensions = array("jpeg", "jpg", "png");
$temporary = explode(".", $_FILES["file"]["name"]);
$file_extension = end($temporary);
if ((($_FILES["file"]["type"] == "image/png") || ($_FILES["file"]["type"] == "image/jpg") || ($_FILES["file"]["type"] == "image/jpeg")
) && ($_FILES["file"]["size"] < 100000)//Approx. 100kb files can be uploaded.
&& in_array($file_extension, $validextensions)) {
if ($_FILES["file"]["error"] > 0)
{
echo "Return Code: " . $_FILES["file"]["error"] . "<br/><br/>";
}
else
{
if (file_exists("upload/" . $_FILES["file"]["name"])) {
echo $_FILES["file"]["name"] . " <span id='invalid'><b>already exists.</b></span> ";
}
else
{
$sourcePath = $_FILES['file']['tmp_name']; // Storing source path of the file in a variable
$targetPath = "upload/".$_FILES['file']['name']; // Target path where file is to be stored
move_uploaded_file($sourcePath,$targetPath) ; // Moving Uploaded file
}
}
}
else
{
echo "<span id='invalid'>***Invalid file Size or Type***<span>";
}
}
?>

JS 代码 -

            var form = document.getElementById('fileupload');
            var fileInput = document.getElementById('headerimage');
            var file = fileInput.files[0];
            var formData = new FormData();
            var filename = '';
            formData.append('file', file);
            var xhr = new XMLHttpRequest();
            xhr.onreadystatechange = function() {
                if (xhr.readyState == 4) {
                    filaname = xhr.responseText;
                }
            }
            // Add any event handlers here...
            xhr.open('POST', form.getAttribute('action'), true);
            xhr.send(formData);

PHP代码 -

<?php
# Data Base Connection
require_once('conn/dbConn.php');
if (!empty($_FILES)) {
    $file = $_FILES;
    if ($file['file']['error'] == 0) {
        $name    = explode('.', $file['file']['name']);
        $newName = "header.".$name[count($name)-1];
        if (move_uploaded_file($file['file']['tmp_name'], "../assets/Themes/Default/".$newName)) {
            echo $newName;
            exit;
        }
    } else {
        echo "";
        exit;
    }
} else {
    echo "";
    exit;
}