上传带有进度条的文件并在php中删除选项

时间:2014-06-20 11:00:39

标签: php html

我正在创建文件上传器,显示进度条和关闭按钮但是这些代码存在一些主要问题。它会继续显示进度条。主要问题是删除文件但是在刷新页面之后我所有上传的文件都不可见,我想从中删除一些文件。  我只想创建文件下载器,如gmail提供多个文件附件的功能,同时使用进度条和关闭按钮,用于由用户误操作上传的文件。

    <script>
     $(document).ready(function() { 

                $('#photoimg').die('click').live('change', function()
                { 
                           //$("#preview").html('');

                    $("#imageform").ajaxForm({target: '#preview', 
                         beforeSubmit:function(){ 

                        console.log('ttest');
                        $("#imageloadstatus").show();
                         $("#imageloadbutton").hide();
                         }, 
                        success:function(){ 
                        console.log('test');
                         $("#imageloadstatus").hide();
                         $("#imageloadbutton").show();
                        }, 
                        error:function(){ 
                        console.log('xtest');
                         $("#imageloadstatus").hide();
                        $("#imageloadbutton").show();
                        } }).submit();


                });
            }); 
    </script>

    <div class="wrap">
    <?php
    /**
    * Multi file upload example
    * @author Resalat Haque
    * @link http://www.w3bees.com/2013/02/multiple-file-upload-with-php.html
    **/

    if(isset($_POST['submit']))
    {
    $valid_formats = array("jpg", "png", "gif", "zip", "bmp","doc","docx");
    $max_file_size = 1024*100; //100 kb
    $path = "uploads/"; // Upload directory
    $count = 0;

    if(isset($_POST) and $_SERVER['REQUEST_METHOD'] == "POST"){
        // Loop $_FILES to execute all files
        foreach ($_FILES['files']['name'] as $f => $name) {     
            if ($_FILES['files']['error'][$f] == 4) {
                continue; // Skip file if any error found
            }          
            if ($_FILES['files']['error'][$f] == 0) {              
                if ($_FILES['files']['size'][$f] > $max_file_size) {
                    $message[] = "$name is too large!.";
                    continue; // Skip large files
                }
                elseif( ! in_array(pathinfo($name, PATHINFO_EXTENSION), $valid_formats) ){
                    $message[] = "$name is not a valid format";
                    continue; // Skip invalid file formats
                }
                else{ // No error found! Move uploaded files 
                    if(move_uploaded_file($_FILES["files"]["tmp_name"][$f], $path.$name)) {
                                $path="uploads/".$name;
                                ?>
                                <div id='imageloadstatus' style='display:none'></div>
    <div id='imageloadbutton'>
    <script type="text/javascript">
    <?php           
                    echo "<a href=\"dl.php?file=".$name."\">".$name."</a>&nbsp;<a href=\"dl.php?file=".$name."\" >                          <img src='image/loader.gif' alt='Uploading....'/><img src=\"image/close.jpg\" /></a><br />"; 
                        $count++; // Number of successfully uploaded files
                    }
                }
            }
        }
    }
    ?>
            <?php
            # error messages
            if (isset($message)) {
                foreach ($message as $msg) {
                    printf("<p class='status'>%s</p></ br>\n", $msg);
                }
            }
            # success message

            if($count !=0){
                printf("<p class='status'>%d files added successfully!</p>\n", $count);
            }
            ?>
            <br />
    <?php } ?>      
            <!doctype html>
    <html lang="en">
      <head>

       <style type="text/css">
          /* Style goes here */ 
        </style>

    </head>
    <body>
            <!-- Multiple file upload html form-->
            <form action="upload_demo.php" method="post" enctype="multipart/form-data" id="imageform">

    <div id='preview'>
    </div>

                <input type="file" name="files[]" multiple="multiple" id="photoimg">
                <input type="submit" value="Upload" name='submit'>


            </form>
    </div>
    </body>
    </html>

要删除dl.php的文件

    <?php if(isset($_GET['file']))
            {
                $file=$_GET['file'];
                $path="uploads/".$file;
                unlink($path);
               // echo "The file: ".$file." has been deleted.";
            ?>
            <script> window.location.href = "upload_demo.php";          
            </script>
            <?php
            }  ?>

1 个答案:

答案 0 :(得分:1)

如果你想使用uploadify,你可以这样做:

你的html文件:

<!doctype html>
<html lang="en">
  <head>

   <style type="text/css">
      /* Style goes here */ 
    </style>

</head>
<body>
    <ul id='image-list'></ul>

        <!-- Multiple file upload html form-->
        <form action="upload_file.php" method="post" enctype="multipart/form-data" id="imageform">

    <input type='file' name='image-upload' id='image-upload' />
</form>

你的javascript文件:

function UploadifyInterface()
{
    var self = this;

    this.init = function()
    {
        $("#image-upload").uploadify({
            height        : 30,
            swf           : 'uploadify.swf',
            uploader      : $("#image-upload").closest("form").attr("action"),
            fileTypeDesc : 'Image Files',
            fileTypeExts : '*.gif; *.jpg; *.png',
            onUploadSuccess     : function(file, data, response) {
            var image = data;
                self.addImage(image.imageId, image.imagePath);
            },
            width         : 120
        });
    }

    this.addImage = function(id, path)
    {
        var imagePath = path.substr(strpos(path, "/", 2));
        $("#image-list").append('<li><img width="120" height="120" src="'+imagePath+'" /><a href="/deleteimg">delete</a></li>');
        $("#image-list > li").width(125);
    }
}

var uploadify = new UploadifyInterface();
uploadify.init();

现在你必须在php方面做一些工作:

将其命名为Uploader.php

<?php

abstract class FileUpload
{
    abstract protected function PreProcessUpload($files);
    abstract protected function GetLastError();
    abstract protected function Response();

    public function ProcessFileUpload($callback, $args)
    {
        if (!isset($_FILES['Filedata']) || !is_uploaded_file($_FILES['Filedata']['tmp_name']))
        {
            $response = array("error" => "File upload not valid!");
        }
        else if(!$this->PreProcessUpload($_FILES['Filedata']))
        {
            $response = $this->GetLastError();
        }
        else
        {
            // processed trough a callbackfunction
            $args[count($args)] = $_FILES['Filedata'];
            call_user_func_array($callback, $args);

            $response = $this->Response();
        }

        header('Cache-Control: no-cache, must-revalidate');
        header('Expires: Mon, 26 Jul 1997 05:00:00 GMT');
        header('Content-Type: application/json');

        echo json_encode($response);
        exit;
    }
}

public class Uploader extends FileUpload
{
    private $error = NULL;
    private $response = NULL;
....
    protected function PreProcessUpload($files)
    {
        $size = @getimagesize($files['tmp_name']);
        $result['size'] = $size;
        if (($size[0] < 25) || ($size[1] < 25))
        {
            $this->response['error'] = 'Please upload an image bigger than 25px.';
            return false;
        }
        return true;
    }

    protected function GetLastError()
    {
        if(is_array($this->response) && isset($this->response['error']))
        {
            return $this->response;
        }
        return array("error" => '');
    }

    protected function Response()
    {
        if(is_array($this->response))
        {
            return $this->response;
        }
        return array();
    }

    public function processImageUpload($id, $uploadImageInfo)
    {
        /*  your processing here */
    }
 ....
}

?>

然后使用类:

将其命名为upload_file.php

 <?php

 include("Uploader.php");

 $uploader = new Uploader();
 $uploader->ProcessFileUpload(array($uploader , "processImageUpload"), array($id));

 ?>

编辑:添加了基本的php / html / javascript文件结构