在JS

时间:2017-06-21 13:21:26

标签: javascript php jquery ajax

我有一个通过某些AJAX发布的上传图片表单。我试图获取上传的文件名和扩展名,以进一步处理它到PHP文件。我无法获得正确的函数来检索上传的文件名和扩展名或大小。这就是我尝试过的。请任何人。

形式

<div class="modal-body">
                    <form data-toggle="validator" action="api/update.php" method="put" enctype="multipart/form-data">
                        <input type="hidden" name="id" class="edit-id">

                        <div class="form-group">
                            <label class="control-label" for="title">Name:</label>
                            <input type="text" name="cat_name" class="form-control" data-error="Please enter title." required />
                            <div class="help-block with-errors"></div>
                        </div>

                        <div class="form-group">
                            <label class="control-label" for="title">Image:</label>
                            <!-- <textarea name="description" class="form-control" data-error="Please enter description." required></textarea>-->
                            <input class="inputField" type="file" id="file" name="file" class="form-control" required>
                            <div class="help-block with-errors"></div>
                        </div>
                        <div>
                        <label>Type:</label>
                        <input type="radio" name="type" value="1" > Special
                        <input  type="radio" name="type" value="0"> Ordinary
                        </div>
                        <br>

<div>
                        <label>Switch:</label>
                        <input type="radio" name="switch" value="1">  On
                        <input  type="radio" name="switch" value="0"> Off
</div>
                        <div class="form-group">
                            <button type="submit" class="btn btn-success crud-submit-edit">Submit</button>
                        </div>

                    </form>

                </div>

AJAX

$(".crud-submit-edit").click(function(e){

    e.preventDefault();
    var form_action = $("#edit-item").find("form").attr("action");
    var name = $("#edit-item").find("input[name='cat_name']").val();
    var image = $("#edit-item").find("input[name='file']").val();
    var type = $("#edit-item").find("input[name='type']:checked").val();
    console.log(type);
    var switches=$("#edit-item").find("input[name='switch']:checked").val();
    console.log(switches);
     var id = $("#edit-item").find(".edit-id").val();

    if(name != '' && type != ''){
        $.ajax({
            dataType: 'json',
            type:'POST',
            url: url + form_action,
            data:{cat_name:name,cat_image:image ,cat_type:type,cat_switch:switches,id:id}
        }).done(function(data){
            getPageData();
            $(".modal").modal('hide');
            toastr.success('Item Updated Successfully.', 'Success Alert', {timeOut: 5000});
        });
    }else{
        alert('You are missing Name or type.')
    }

});
});

update.php

$id  = $_POST["id"];
$post = $_POST;
define ("MAX_SIZE","2000"); // 2MB MAX file size
function getExtension($str)
{
    $i = strrpos($str,".");
    if (!$i) { return ""; }
    $l = strlen($str) - $i;
    $ext = substr($str,$i+1,$l);
    return $ext;
}
// Valid image formats
$valid_formats = array("jpg", "png", "gif", "bmp","jpeg");

    $uploaddir = "images/"; //Image upload directory

        $filename = stripslashes($_FILES['cat_image']['name']);
        $size=filesize($_FILES['cat_image']['tmp_name']);
//Convert extension into a lower case format
        $ext = getExtension($filename);
        $ext = strtolower($ext);
//File extension check
        if(in_array($ext,$valid_formats))
        {
//File size check
            if ($size < (MAX_SIZE*1024))
            {
                $image_name=time().$filename;
                echo "<img src='".$uploaddir.$image_name."' class='imgList'>";
                $newname=$uploaddir.$image_name;
//Moving file to uploads folder
                if (move_uploaded_file($_FILES['cat_image']['tmp_name'], $newname))
                {
                    $time=time();
//Insert upload image files names into user_uploads table

                    $sql = "UPDATE categories SET cat_name = '".$post['cat_name']."',cat_image='".$image_name."',cat_type = '".$post['cat_type']."' ,cat_switch='".$post['cat_switch']."' WHERE cat_id = '".$id."'";

                    $result = $con->query($sql);


                    $sql = "SELECT * FROM categories WHERE cat_id = '".$id."'";

                    $result = $con->query($sql);

                    $data = $result->fetch_assoc();


                    echo json_encode($data);
                }
                else
                {
                    echo '<span class="imgList">You have exceeded the size limit! so moving unsuccessful! </span>'; }
            }

            else
            {
                echo '<span class="imgList">You have exceeded the size limit!</span>';
            }

        }

        else
        {
            echo '<span class="imgList">Unknown extension!</span>';
        }

2 个答案:

答案 0 :(得分:0)

要像使用AJAX一样上传文件,您应该使用FormData从表单中收集所有数据并将其发送到php处理程序https://developer.mozilla.org/en-US/docs/Web/API/FormData/Using_FormData_Objects 类似主题How to use FormData for ajax file upload

答案 1 :(得分:0)

我对php知之甚少,但您可以在javascript中获取该代码的文件详细信息;

&#13;
&#13;
$("#showMe").click(function(){
  var file=$("#myFile").val().replace(/C:\\fakepath\\/i, '').split(".");
  console.log("File Name:"+file[0],"File Extension:"+file[1])
})
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="file" id="myFile"/>

<button id="showMe">Show Me File Details</button>
&#13;
&#13;
&#13;