【问题标题】:AJAX can't upload the image without submit eventAJAX 无法在没有提交事件的情况下上传图片
【发布时间】:2015-10-12 06:13:34
【问题描述】:

我希望能够异步上传具有 AJAX 功能的图像。我访问了很多关于使用 AJAX 上传图像的网站,并尝试了很多代码组合,但是虽然分享解决方案的人说它运行正常,但我认为它们都是垃圾。因为,我无法使用 AJAX 上传任何图像没有提交事件。我想强调这一点,我已经可以使用 表单提交 类型的按钮上传图像就像在这里:AJAX Uploading in StackOverflow 但我不想要它。我只想在不提交表单的情况下使用上传图片的过程,这样我就可以在提交文章之前在我的博客编辑器界面中使用这张图片。我相信这是可能的,因为这是 AJAX,我们在 2015 年。但我需要一个答案说这是可能的,我需要一个解决方案或解决方案的方法。这是我从我的博客站点中提取的代码,我想说它是最接近解决方案的代码。因为,in this stackoverflow question,有一个强大的比率表明这是有用的:(顺便说一下,我不想上传插件,我知道有太多的插件可以做到这一点。但我想努力去做- 编码和我自己,而不是通过插件)

JS:

<script>
    $(document).ready(function() {
    $(':button').click(function(){
        var formData = new FormData($('form')[0]);

        $.ajax({
            url: 'bilesenler/yaziEkle/ajaxUpload.php',  //Server script to process data
            type: 'POST',
            enctype: 'multipart/form-data',

            xhr: function() {  // Custom XMLHttpRequest
                var myXhr = $.ajaxSettings.xhr();

                if(myXhr.upload){ // Check if upload property exists
                    myXhr.upload.addEventListener('progress',progressHandlingFunction, false); // It makes progressBar full.
                }
                return myXhr;
            },

            success: function(result){
                        $("#div1").html(result);   // This works very well.
                     },
            error: function(error){
                        $("#div2").html(error);   // This is not being running after the uploading process. So there is no problem.
                   },

            // Form data
            data: formData,

            //Options to tell jQuery not to process data or worry about content-type.
            cache: false,
            contentType: false,
            processData: false
        });
    });

    function progressHandlingFunction(e){
        if(e.lengthComputable){
            $('progress').attr({value:e.loaded,max:e.total});
        }
    }
});
</script>

HTML:

<form action="../adminPaneli/yaziEkle.php" method="POST" name="addText" enctype="multipart/form-data">

    <!-- 
        There are some html codes... 
    -->

    <input type="button" id="upload" value="Upload">&nbsp;&nbsp;
    <input type="file" name="file" id="file">
    <progress></progress>

    <!-- 
        There are some html codes... 
    -->

    <div id="div1"></div><br>
    <div id="div2"></div>


    <input type="submit" name="publishArticle" value="Publish">
</form>

PHP:

<?php
if (file_exists("../kitaplik/resimler/upload/" . $_FILES["file"]["name"])){
    echo $fileName . " already exists.<br>";
}
else{
    move_uploaded_file($_FILES["file"]["tmp_name"], "../kitaplik/resimler/upload/" . $_FILES["file"]["name"]);
    echo "Stored in: " . "../kitaplik/resimler/upload/" . $_FILES["file"]["name"] . " <br>";
}
?>

当我点击上传按钮时,进度条已满。即存在上传过程。然后,服务器响应请求,html 页面显示以下输出:

Notice: Undefined index: file in /.../bilesenler/yaziEkle/ajaxUpload.php on line 1

Notice: Undefined index: file in /.../bilesenler/yaziEkle/ajaxUpload.php on line 5

Notice: Undefined index: file in /.../bilesenler/yaziEkle/ajaxUpload.php on line 5

Notice: Undefined index: file in /.../bilesenler/yaziEkle/ajaxUpload.php on line 6

Stored in: ../kitaplik/resimler/upload/

也就是说,$.ajax 运行的“成功”标签,而不是“错误”标签。因为,当我通过对其行注释来删除 $.ajax 中的错误标签时,会出现相同的输出。

通常,我可以使用带有提交属性类型的服务器端代码上传图像。但是使用 ajax 功能,文件的接收者 $_FILE 无法捕获该文件。任何人都可以提出解决这个问题的想法或任何新技术吗?

【问题讨论】:

    标签: php jquery html ajax upload


    【解决方案1】:

    试试这个..

    在根目录下创建“上传”目录

    索引.php

    <!DOCTYPE HTML>
    <html>
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>Ajax Upload and Resize with jQuery and PHP - Demo</title>
    <script type="text/javascript" src="http://www.sanwebe.com/wp-content/themes/sanwebe/js/jquery-1.10.2.min.js"></script>
    <script type="text/javascript" src="http://www.sanwebe.com/assets/ajax-image-upload/js/jquery.form.min.js"></script>
    
    <script type="text/javascript">
    $(document).ready(function() { 
        var options = { 
                target: '#output',   // target element(s) to be updated with server response 
                beforeSubmit: beforeSubmit,  // pre-submit callback 
                success: afterSuccess,  // post-submit callback 
                resetForm: true        // reset the form after successful submit 
            }; 
    
         $('#MyUploadForm').submit(function() { 
                $(this).ajaxSubmit(options);            
                // always return false to prevent standard browser submit and page navigation 
                return false; 
            }); 
    }); 
    
    function afterSuccess()
    {
        $('#submit-btn').show(); //hide submit button
        $('#loading-img').hide(); //hide submit button
    
    }
    
    //function to check file size before uploading.
    function beforeSubmit(){
        //check whether browser fully supports all File API
       if (window.File && window.FileReader && window.FileList && window.Blob)
        {
    
            if( !$('#imageInput').val()) //check empty input filed
            {
                $("#output").html("Are you kidding me?");
                return false
            }
    
            var fsize = $('#imageInput')[0].files[0].size; //get file size
            var ftype = $('#imageInput')[0].files[0].type; // get file type
    
    
            //allow only valid image file types 
            switch(ftype)
            {
                case 'image/png': case 'image/gif': case 'image/jpeg': case 'image/pjpeg':
                    break;
                default:
                    $("#output").html("<b>"+ftype+"</b> Unsupported file type!");
                    return false
            }
    
            //Allowed file size is less than 1 MB (1048576)
            if(fsize>1048576) 
            {
                $("#output").html("<b>"+bytesToSize(fsize) +"</b> Too big Image file! <br />Please reduce the size of your photo using an image editor.");
                return false
            }
    
            $('#submit-btn').hide(); //hide submit button
            $('#loading-img').show(); //hide submit button
            $("#output").html("");  
        }
        else
        {
            //Output error to older browsers that do not support HTML5 File API
            $("#output").html("Please upgrade your browser, because your current browser lacks some new features we need!");
            return false;
        }
    }
    
    //function to format bites bit.ly/19yoIPO
    function bytesToSize(bytes) {
       var sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB'];
       if (bytes == 0) return '0 Bytes';
       var i = parseInt(Math.floor(Math.log(bytes) / Math.log(1024)));
       return Math.round(bytes / Math.pow(1024, i), 2) + ' ' + sizes[i];
    }
    
    </script>
    <link href="http://www.sanwebe.com/assets/ajax-image-upload/style/style.css" rel="stylesheet" type="text/css">
    </head>
    <body>
    <div id="upload-wrapper">
    <div align="center">
    <h3>Ajax Image Uploader</h3>
    <form action="processupload.php" method="post" enctype="multipart/form-data" id="MyUploadForm">
    <input name="image_file" id="imageInput" type="file" />
    
    <img src="images/ajax-loader.gif" id="loading-img" style="display:none;" alt="Please Wait"/>
    </form>
    <div id="output"></div>
    </div>
    </div>
    <script>
    $("#imageInput").change(function(){
    $("#MyUploadForm").submit();
    });
    </script>
    </body>
    </html>
    

    processupload.php

    <?php
    ############ Configuration ##############
    $thumb_square_size      = 200; //Thumbnails will be cropped to 200x200 pixels
    $max_image_size         = 500; //Maximum image size (height and width)
    $thumb_prefix           = "thumb_"; //Normal thumb Prefix
    $destination_folder     = 'uploads/'; //upload directory ends with / (slash)
    $jpeg_quality           = 90; //jpeg quality
    ##########################################
    
    //continue only if $_POST is set and it is a Ajax request
    if(isset($_POST) && isset($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest'){
    
        // check $_FILES['ImageFile'] not empty
        if(!isset($_FILES['image_file']) || !is_uploaded_file($_FILES['image_file']['tmp_name'])){
                die('Image file is Missing!'); // output error when above checks fail.
        }
    
        //uploaded file info we need to proceed
        $image_name = $_FILES['image_file']['name']; //file name
        $image_size = $_FILES['image_file']['size']; //file size
        $image_temp = $_FILES['image_file']['tmp_name']; //file temp
    
        $image_size_info    = getimagesize($image_temp); //get image size
    
        if($image_size_info){
            $image_width        = $image_size_info[0]; //image width
            $image_height       = $image_size_info[1]; //image height
            $image_type         = $image_size_info['mime']; //image type
        }else{
            die("Make sure image file is valid!");
        }
    
        //switch statement below checks allowed image type 
        //as well as creates new image from given file 
        switch($image_type){
            case 'image/png':
                $image_res =  imagecreatefrompng($image_temp); break;
            case 'image/gif':
                $image_res =  imagecreatefromgif($image_temp); break;           
            case 'image/jpeg': case 'image/pjpeg':
                $image_res = imagecreatefromjpeg($image_temp); break;
            default:
                $image_res = false;
        }
    
        if($image_res){
            //Get file extension and name to construct new file name 
            $image_info = pathinfo($image_name);
            $image_extension = strtolower($image_info["extension"]); //image extension
            $image_name_only = strtolower($image_info["filename"]);//file name only, no extension
    
            //create a random name for new image (Eg: fileName_293749.jpg) ;
            $new_file_name = $image_name_only. '_' .  rand(0, 9999999999) . '.' . $image_extension;
    
            //folder path to save resized images and thumbnails
            $thumb_save_folder  = $destination_folder . $thumb_prefix . $new_file_name; 
            $image_save_folder  = $destination_folder . $new_file_name;
    
            //call normal_resize_image() function to proportionally resize image
            if(normal_resize_image($image_res, $image_save_folder, $image_type, $max_image_size, $image_width, $image_height, $jpeg_quality))
            {
                //call crop_image_square() function to create square thumbnails
                if(!crop_image_square($image_res, $thumb_save_folder, $image_type, $thumb_square_size, $image_width, $image_height, $jpeg_quality))
                {
                    die('Error Creating thumbnail');
                }
    
                /* We have succesfully resized and created thumbnail image
                We can now output image to user's browser or store information in the database*/
                echo '<div align="center">';
                echo '<img src="uploads/'.$thumb_prefix . $new_file_name.'" alt="Thumbnail">';
                echo '<br />';
                echo '<img src="uploads/'. $new_file_name.'" alt="Resized Image">';
                echo '</div>';
            }
    
            imagedestroy($image_res); //freeup memory
        }
    }
    
    #####  This function will proportionally resize image ##### 
    function normal_resize_image($source, $destination, $image_type, $max_size, $image_width, $image_height, $quality){
    
        if($image_width <= 0 || $image_height <= 0){return false;} //return false if nothing to resize
    
        //do not resize if image is smaller than max size
        if($image_width <= $max_size && $image_height <= $max_size){
            if(save_image($source, $destination, $image_type, $quality)){
                return true;
            }
        }
    
        //Construct a proportional size of new image
        $image_scale    = min($max_size/$image_width, $max_size/$image_height);
        $new_width      = ceil($image_scale * $image_width);
        $new_height     = ceil($image_scale * $image_height);
    
        $new_canvas     = imagecreatetruecolor( $new_width, $new_height ); //Create a new true color image
    
        //Copy and resize part of an image with resampling
        if(imagecopyresampled($new_canvas, $source, 0, 0, 0, 0, $new_width, $new_height, $image_width, $image_height)){
            save_image($new_canvas, $destination, $image_type, $quality); //save resized image
        }
    
        return true;
    }
    
    ##### This function corps image to create exact square, no matter what its original size! ######
    function crop_image_square($source, $destination, $image_type, $square_size, $image_width, $image_height, $quality){
        if($image_width <= 0 || $image_height <= 0){return false;} //return false if nothing to resize
    
        if( $image_width > $image_height )
        {
            $y_offset = 0;
            $x_offset = ($image_width - $image_height) / 2;
            $s_size     = $image_width - ($x_offset * 2);
        }else{
            $x_offset = 0;
            $y_offset = ($image_height - $image_width) / 2;
            $s_size = $image_height - ($y_offset * 2);
        }
        $new_canvas = imagecreatetruecolor( $square_size, $square_size); //Create a new true color image
    
        //Copy and resize part of an image with resampling
        if(imagecopyresampled($new_canvas, $source, 0, 0, $x_offset, $y_offset, $square_size, $square_size, $s_size, $s_size)){
            save_image($new_canvas, $destination, $image_type, $quality);
        }
    
        return true;
    }
    
    ##### Saves image resource to file ##### 
    function save_image($source, $destination, $image_type, $quality){
        switch(strtolower($image_type)){//determine mime type
            case 'image/png': 
                imagepng($source, $destination); return true; //save png file
                break;
            case 'image/gif': 
                imagegif($source, $destination); return true; //save gif file
                break;          
            case 'image/jpeg': case 'image/pjpeg': 
                imagejpeg($source, $destination, $quality); return true; //save jpeg file
                break;
            default: return false;
        }
    }
    

    【讨论】:

    • 据我所知,此代码通过提交表单来上传图像。我需要通过不提交表单来上传文件。因为上传过程后我的表格工作没有完成。而且,我已经尝试过代码。它没有用。我的意思是,在控制台中存在主题错误,并且在上传目录中没有图像。这段代码可以在你的机器上运行吗?
    • 单击屏幕上的按钮后尝试选择图像时,屏幕下方会出现另一个上传按钮。当我使用下面的新上传按钮选择图像时,正在选择图像,但上传目录中没有图像。至于错误: GET localhost/upload/4/images/ajax-loader.gif 404 (Not Found) 正如我所说,这个错误超出了主题。
    • 有两个文件首先是 index.php 和 processupload.php 然后在根目录中创建上传目录它为我工作。
    • 所有文件都放在示例目录中,如“test”。并运行 localhost/test
    • 有趣。我已经创建了 processupload.php、index.php 和上传目录。但不幸的是,它不像其他机器那样在我的机器上工作。让我深入看看代码。也许我可以找到任何错误,从而我可以集中精力解决问题。
    猜你喜欢
    • 1970-01-01
    • 2020-08-03
    • 1970-01-01
    • 2014-04-09
    • 1970-01-01
    • 2012-08-04
    • 2016-08-29
    • 1970-01-01
    • 2011-11-08
    相关资源
    最近更新 更多