【问题标题】:multipart fileupload with formdata使用 formdata 进行多部分文件上传
【发布时间】:2018-02-27 07:01:44
【问题描述】:

我正在尝试使用 formdata 上传文件。该文件单独有效,但我需要上传一些用户数据。我试图附加formdata,但是当我“print_r”时,ajax调用的php文件中的数组($_FILES)没有出现。

如果有人对此问题有解决方案,或者有更好的方法来处理用户数据上传文件,请告诉我!

您可以在下面找到使用的代码:

php:

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<link href="style.css" rel="stylesheet" type="text/css">
<script src="jquery-1.12.0.min.js"></script>


</head>
<body>
<div class="container">
    <h1>AJAX File upload</h1>

    <form method="post" action="" enctype="multipart/form-data" id="myform">
        <input type="text" id="test" value="sample">
        <div >
            <img src="" id="img" width="100" height="100">
        </div>
        <div >
            <input type="file" id="file" name="file" />
            <input type="button" class="button" value="Upload" id="but_upload">
        </div>
    </form>
</div>
</body>
<script type="text/javascript">
$(document).ready(function(){
    $("#but_upload").click(function(){
        //console.log("piemel");
        console.log(document.getElementById('test').value);
        var fd = new FormData();
        var files = $('#file')[0].files[0];
       fd.append('test', document.getElementById('test').value);
        fd.append('file',files);
        console.log(fd);

        $.ajax({
            url:'upload.php',
            type:'post',
            data:fd,
            contentType: false,
            processData: false,
            success:function(response){
                if(response != 0){
                    $("#img").attr("src",response);
                }
            },
            error:function(response){
                alert('error : ' + JSON.stringify(response));
            }
        });
    });
});


</script>
</html>

Ajax 文件:

<?php

/* Getting file name */

$filename = $_FILES['file']['name'];

/* Location */
$location = "upload/".$filename;

/* Upload file */
if(move_uploaded_file($_FILES['file']['tmp_name'],$location)){
   echo $location;
}else{
    echo 0;
}

【问题讨论】:

    标签: javascript php jquery ajax file-upload


    【解决方案1】:

    我有一个示例工作演示代码(我也遇到了这个问题并创建了这个脚本)

    index.php

    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
    
    <form id="uploadForm" action="upload.php" method="post">
    <label>Upload Image File:</label><br/>
    <input name="userImage" type="file" class="inputFile" />
    <input type='text' name="my_name" value="harish">
    <input type="submit" value="Submit" class="btnSubmit" />
    </form>
    
    <script type="text/javascript">
    
    $(document).ready(function (e) {
    
        $("#uploadForm").on('submit',(function(e) {
    
        e.preventDefault();
    
        $.ajax({
    
                url: "upload.php",
                type: "POST",
                data:  new FormData(this),
                contentType: false,
                cache: false,
                processData:false,
    
                success: function(data){
                    $("#targetLayer").html(data);
                },
                error: function(){}             
            });
    
        }));
    
    });
    
    </script>
    

    上传.php

    <?php
    error_reporting(E_ALL);
    ini_set('display_errors', 1);
    
    if(isset($_FILES["userImage"]["type"]))
    {
        $validextensions = array("jpeg", "jpg", "png");
        $temporary = explode(".", $_FILES["userImage"]["name"]);
        $file_extension = end($temporary);
    
        $file_type = $_FILES["userImage"]["type"];
    
        if ((($file_type == "image/png") || ($file_type == "image/jpg") || ($file_type == "image/jpeg")
        ) /*&& ($_FILES["file"]["size"] < 100000)*/ //Approx. 100kb files can be uploaded.
        && in_array($file_extension, $validextensions))
        {
            if ($_FILES["userImage"]["error"] > 0)
            {
                echo "Return Code: " . $_FILES["userImage"]["error"] . "<br/><br/>";
            }
            else
            {
                if (file_exists("uploads/" . $_FILES["userImage"]["name"] . '-'.time()))
                {
                    echo $_FILES["userImage"]["name"] . time() ." <span id='invalid'><b>already exists.</b></span> ";
                }
                else
                {
                    $sourcePath = $_FILES['userImage']['tmp_name']; // Storing source path of the file in a variable
                    $targetPath = "uploads/".$_FILES['userImage']['name'].'-'.time(); // Target path where file is to be stored
    
                    //check the writable permissions
    
                    /*if (is_writeable('uploads/' . $_FILES['userImage']['name'])) {
                       die("Cannot write to destination file");
                    }*/
    
                    if(move_uploaded_file($sourcePath,$targetPath)) {
    
                        echo "<span id='success'>Image Uploaded Successfully...!!</span><br/>";
                        echo "<br/><b>File Name:</b> " . $_FILES["userImage"]["name"] . "<br>";
                        echo "<b>Type:</b> " . $_FILES["userImage"]["type"] . "<br>";
                        echo "<b>Size:</b> " . ($_FILES["userImage"]["size"] / 1024) . " kB<br>";
                        echo "<b>Temp file:</b> " . $_FILES["userImage"]["tmp_name"] . "<br>";
    
                    } else {
    
                        echo "<pre>"; print_r($_FILES['file']['error']); echo "</pre>";
                    }
                }
            }
        }
        else
        {
        echo "<span id='invalid'>***Invalid file Size or Type***<span>";
        }
    }
    ?>
    

    *在同级创建文件夹upload或更改上传路径并确保赋予其可写权限。

    此脚本适用于数据和文件,对于发布数据,您需要使用 $_POST['post_input']。

    试试这个脚本,希望它对你有所帮助。

    【讨论】:

    • 这非常适合我的需求。我只改变了 $file_extension =end($temporary); to $file_extension = strtolower(end($temporary));
    【解决方案2】:

    $_FILES 用于文件而不是数据,因为您通过邮寄使用$_POST 发送数据

    【讨论】:

      【解决方案3】:

      嗯。你想上传大文件吗?因为当我在搞乱 $_FILES 时,上传大于 20mb 的文件是不成功的,直到我将 IIS 中的最大上传文件设置为我可以传输大文件的最大值。我唯一可以在不弄乱 IIS 的情况下上传的是普通图像。

      您的代码似乎没有错,因为它必须将临时文件放入您提供的位置,所以您到底想上传什么?您在代码中使用的文件夹“上传”是否存在?如果文件夹不存在,它也不会移动任何文件

      【讨论】:

        猜你喜欢
        • 2021-05-18
        • 2013-05-08
        • 2014-01-29
        • 2018-03-18
        • 2012-10-10
        相关资源
        最近更新 更多