dtv7174 2017-03-06 09:04
浏览 47

无法使用ajax上传照片

I am trying to make an upload form, which uploads a photo with ajax, but a problem I currently have is, it doesn't really make a sense about it. Here is a code so do you have any ideas why it doesn't work ?

<form id="commentForm" enctype="multipart/form-data">
                                        <input type="file" name="fileToUpload">
    <button type="submit" name="commentSubmit" id="commentButton" class="btn green"><i class="fa fa-paper-plane"></i> </button>
</form>
<div id="output">GGG</div>
<script type="text/javascript">
    $('#commentForm').on('submit',(function(e) {

        e.preventDefault();

        $.ajax({
            type: 'post',
            url: 'test2.php',
            cache: false,
            contentType: false,
            processData: false,
            data: $('#commentForm').serialize(),
            success: function (html) {
                $('#output').html(html);

            }
        })
    }));
</script>

and here is "test2.php"

<?php


$day_hour = date("H");
$day_min = date("i");
$day_sec = date("s");


if (isset($_FILES["fileToUpload"]["tmp_name"])) {
error_reporting(0);
$target_dir = "upload/";
$target_file = $target_dir . $photo_name_codi . "TSG" . $day_hour . $day_min . $day_sec . "_" . rand(100, 999) . ".jpg";
$uploadOk = 1;
$imageFileType = pathinfo($target_file, PATHINFO_EXTENSION);
// Check if image file is a actual image or fake image
if (isset($_POST["submit"])) {
$check = getimagesize($_FILES["fileToUpload"]["tmp_name"]);
if ($check !== false) {
$uploadOk = 1;
} else {
echo "File is not an image.";
$uploadOk = 0;
}
}
// Check if file already exists
if (file_exists($target_file)) {
echo "Sorry, file already exists.";
$uploadOk = 0;
}
// Check file size
if ($_FILES["fileToUpload"]["size"] > 500000) {
echo "Sorry, your file is too large.";
$uploadOk = 0;
}
// Allow certain file formats
if ($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg"
&& $imageFileType != "gif"
) {
echo "Sorry, only JPG, JPEG, PNG & GIF files are allowed.";
$uploadOk = 0;
}
// Check if $uploadOk is set to 0 by an error
if ($uploadOk == 0) {
echo "Sorry, your file was not uploaded.";
// if everything is ok, try to upload file
} else {
if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file)) {
echo "The file " . $target_file . " has been uploaded. " . $imageFileType;
} else {
echo "Sorry, there was an error uploading your file.";
}
}
}

</div>
  • 写回答

1条回答 默认 最新

  • duanliao5995 2017-03-06 09:06
    关注

    Try this:

    Html:

    <input id="pic" type="file" name="pic" />
    <button id="upload">Upload</button>
    

    Jquery:

    $('#upload').on('click', function() {
            var file_data = $('#pic').prop('files')[0];
            var form_data = new FormData();
            form_data.append('file', file_data);
    
            $.ajax({
                    url         : 'upload.php',     // point to server-side PHP script 
                    dataType    : 'text',           // what to expect back from the PHP script, if anything
                    cache       : false,
                    contentType : false,
                    processData : false,
                    data        : form_data,                         
                    type        : 'post',
                    success     : function(output){
                        alert(output);              // display response from the PHP script, if any
                    }
             });
             $('#pic').val('');                     /* Clear the file container */
        });
    

    Php:

    <?php
        if ( $_FILES['file']['error'] > 0 ){
            echo 'Error: ' . $_FILES['file']['error'] . '<br>';
        }
        else {
            if(move_uploaded_file($_FILES['file']['tmp_name'], 'uploads/' . $_FILES['file']['name']))
            {
                echo "File Uploaded Successfully";
            }
        }
    
    ?>
    
    评论

报告相同问题?

悬赏问题

  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度