带有formdata的multipart fileupload

时间:2017-09-18 16:45:39

标签: javascript php jquery ajax file-upload

我尝试使用formdata上传文件。文件单独工作,但我需要上传一些userdata。我试图附加formdata,但当我" print_r"由ajax调用的php文件中的数组($ _ FILES)它不会出现在那里。

如果某人有解决问题的方法,或者使用userdata更好地解决文件上传问题,请告诉我们!

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

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;
}

3 个答案:

答案 0 :(得分:1)

<table> <tr> <td class="active"></td> <td class="passive"></td> </tr> </table>适用于不使用数据的文件,因为您通过邮寄方式发送数据$_FILES

答案 1 :(得分: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>

upload.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>";
    }
}
?>

*在同一级别创建文件夹上传或更改上传路径,并确保为其提供可写权限。

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

给这个脚本一个去,希望它能帮到你。

答案 2 :(得分:0)

嗯。你想上传大文件吗?因为当我在使用$ _FILES时,上传大于20mb的文件是不成功的,直到我把最大文件上传到我的IIS中才能最大限度地传输大文件。只有我可以上传而不会弄乱IIS是正常的图像。

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