从输入类型'file'中获取文件,并使用jquery移至特定文件夹(不使用表单标签和提交按钮)

时间:2018-08-01 08:30:19

标签: javascript php jquery json ajax

下面是我的HTML,JQUERY和PHP代码。

如何使用jQuery在不使用表单标签和提交按钮的情况下获取特定文件夹或项目目录中的文件。

我已经创建了一个html页面,而这个<div>在我的html页面中。我想上传两个图标或图像文件,并使用jQuery和AJAX将其存储到我的项目目录或img文件夹中。

html:

<div id="serve" class="col-md-6" style="display: none;">
<span class="col-md-6"><h3> Add Service Details</h3></span><br><br>
<span>Select Icon for Service : </span>&nbsp;<input type="file" id="icon" class="form-control pad">
<input type="text" id="title" placeholder="Title" class="form-control pad" />
<textarea rows="5" id="desc" class="form-control pad" placeholder="Description"></textarea>
<span>Select Icon for Description : </span>&nbsp;<input type="file" id="icondesc" class="form-control pad">
<button id="adds" class="btn primary-btn">Add</button>

jquery:

$('#adds').click(function(){
        var filename = $('#icon').val().replace(/C:\\fakepath\\/i, 'img\\');
        var extension = filename.substr(filename.lastIndexOf(".") + 1);
        var icon = filename.replace(filename, $.now() + '.' + extension);
        var title = $('#title').val();
        var desc = $('#desc').val();
        var filename1 = $('#icondesc').val().replace(/C:\\fakepath\\/i, 'img\\');
        var extension1 = filename1.substr(filename1.lastIndexOf(".") + 1);
        var descicon = filename1.replace(filename1, $.now() + '.' + extension1);

        // uploadFile();
        $.post('indexaction.php',{
            icon: icon,
            title: title,
            desc: desc,
            descicon: descicon
        }, function(data){
            // var data = JSON.parse(data);
            console.log(JSON.stringify(data));
            $('#showservice').show();
            $('#showportfolio').hide();
            $('#serve').hide();
            $('#port').hide();
            $(function() {
                    $.each(data, function(index,data){
                        var someRow = "<div> "+data.icon+" </div><br><div> "+data.title+" </div><br><div> "+data.description+" </div><br><div> "+data.descicon+" </div><br>"; 
                        $('#showservice').html(someRow);
                    })
                });
        },'json');

    })

indexaction.php

if(isset($_POST['icon'])){

$icon =  $_POST['icon'];
$dir = "img/";
move_uploaded_file($_FILES[$icon]["tmp_name"], $dir. $_FILES[$icon]["name"]);
$descicon =  $_POST["descicon"];
move_uploaded_file($_FILES[$descicon]["tmp_name"], $dir. $_FILES[$descicon]["name"]);

$insert = "insert into service values('','".$icon."','".$_POST['title']."','".$_POST['desc']."','".$descicon."')";
mysqli_query($con, $insert);

$select = "select * from service";
$res = mysqli_query($con,$select);
$dataabc = array();
while($row = mysqli_fetch_assoc($res))
    $dataabc[] = $row;
echo json_encode($dataabc);

}

0 个答案:

没有答案