Jquery事件监听器打开文件资源管理器弹出窗口

时间:2017-06-21 14:22:43

标签: javascript c# asp.net json

我的要求是打开像dropzone这样的文件浏览器,我已经完成了拖放事件监听器,如dragenter,dragover,dragleave,drop。一切正常,但我也想要一个文件浏览器弹出窗口。

以下是我的代码(我已经包含了jquery-1.7.1.min.js和jquery-ui-1.8.20.min.js)

风格:

    #dropzone {
        /*border: 2px dashed #ccc;*/
        width: 100%;
        min-height: 100px;
        height: auto;
        padding: 5px;
        overflow: hidden;
        background: #ccc;
    }

    .over {
        border: 2px dashed #000;
        content: "DROP FILE OVER HERE";
    }

    #drag-content {
        font-family: fantasy;
        font-size: 50px;
        text-align: center;
        position: relative;
        top: 0%;
        left: 30%;
        text-align: center;
        vertical-align: middle;
    }

    .displayNone {
        display: none;
    }

    .displayBlock {
        display: block;
    }

    #MSG {
        display: none;
        position: absolute;
        right: 50%;
        top: 111px;
    }

    #overlay {
        position: fixed;
        top: 0;
        left: 0;
        width: 100%;
        height: 100%;
        background-color: #000;
        filter: alpha(opacity=70);
        -moz-opacity: 0.7;
        -khtml-opacity: 0.7;
        opacity: 0.7;
        z-index: 100;
        display: block;
    }

    .imageControl {
        width: 200px;
        height: 200px;
        float: left;
        position: relative;
        padding-right: 10px;
    }

        .imageControl img {
            width: 200px;
            height: 200px;
        }

        .imageControl a {
            position: absolute;
            margin-left: 0px;
        }

            .imageControl a img {
                width: 20px;
                height: 20px;
                position: absolute;
                top: 3%;
                margin-left: -2%;
            }

脚本:

    $(document).ready(function () {
        var dz = document.querySelector('#dropzone');
        dz.addEventListener('dragenter', handleDragEnter, false);//Register Event dragenter
        dz.addEventListener('dragover', handleDragOver, false);//Register Event dragover
        dz.addEventListener('dragleave', handleDragLeave, false);//Register Event dragleave
        dz.addEventListener('drop', handleDrop, false);//Register Event drop

        //GetFileDetails();// Load all The Images on PageLoad

       // $("#dropzone").sortable();
        // $("#dropzone").disableSelection();

    });

    function handleDragOver(e) {
        if (e.preventDefault) {
            e.preventDefault(); // Necessary. Allows us to drop.
        }
        this.classList.add('over');

        return false;
    }
    function handleDragEnter(e) {
        // If you have used the DropZone you must have noticed that when you drag an item into the browser the gray area(The DropZone)is hilighted by dotted line at its border
        // well here is how I do it I just add border to the div...
        // I Have created ta class called over which basically has the styles to hilight the div. 
        // but only when the you are draging any file on the browser
        this.classList.add('over');


    }
    function handleDragLeave(e) {
        // while draging If you move the cursour out of the DropZone, then the hilighting must be removed
        // so here I am removing the class over from the div
        e.preventDefault();
        this.classList.remove('over');

    }
    //On Drop of file over the DropZone(I have Elaborated the process of What Happen on Drop in Points)
    function handleDrop(e) {
        //1st thing to do is Stop its default event, If you won't then the browser will end up rendering the file
        e.preventDefault();
        //2nd Checking if the the object e has any files in it.
        //    actually the object named "dataTransfer" in the object e is the object that hold the data that is being dragged during a drag and drop operation
        //    dataTransfer object can hold one or more files
        if (e.dataTransfer.files.length == 0) {
            this.classList.remove('over');
            return;// if no files are found then there is no point executing the rest of the code so I return to the function.
        }
        var files = e.dataTransfer.files;
        //3rd  Here I am using an object of FormData() to send the files to the server using AJAX
        //     The FormData object lets you compile a set of key/value pairs to send using AJAX
        //     Its primarily intended for use in sending form data
        var data = new FormData();
        for (var i = 0, f; f = files[i]; i++) {
            data.append(files[i].name, files[i]);//Here I am appending the files from the dataTransfer object to FormData() object in Key(Name of File) Value(File) pair
        }
        // The operation of Uploading the file consumes time till the time the browser almost freezes 
        this.classList.remove('over');

        //4th  Once I have got all my files in the object of FormData() now I am ready to send the files to server to using AJAX
        var options = {};
        options.url = 'FileUploader.ashx';//URL  
        options.type = 'post';//Post Method
        options.data = data;
        options.async = false;//synchronous Call   
        options.contentType = false;
        options.processData = false;
        options.beforeSend = function () {
            ShowPopup();//POPUP used to show the uploading is under progress
        };
        options.error = function () {
            alert('Problem uploading file');
            HidePopup();
        };
        options.complete = function (response) {
            HidePopup();//Once the process is completed POPUP is removed
            GetFileDetails();//This function is used to bind the div#DropZone with images. I am calling it again to update the page with new Images
        };
        $.ajax(options);


    }

   var overlay = $('<div id="overlay"></div>');
    //By default the popup is hidden.
    //ShowPopup is used to show popup
    function ShowPopup() {
        //the body is appended with the the div#overlay which gives the dark background to the popup
        overlay.appendTo(document.body).remove();
        $('#MSG').show();
    }
    //HidePopup is used to hide the popup
    function HidePopup() {
        $('#MSG').hide();
        overlay.appendTo(document.body).remove();
    }
    var today = new Date();
    var dd = today.getDate();
    var mm = today.getMonth() + 1;
    var yyyy = today.getFullYear();
    if (dd < 10) { dd = '0' + dd }
    if (mm < 10) { mm = '0' + mm }
    var today = dd + '' + mm + '' + yyyy;

    var imgControl = '<div class="imageControl">\
                            <a href="javascript:deleteImage(\'||FILENAME||\');">\
                                <img src="delete.png" />\
                            </a>\
                            <img src="Images/Stories/' + today + '/||FILENAME||" />\
                         </div>';
    //GetFileDetails is used retrieve all the names of the file in the folder "Images" 
    //It also renders the HTML with Images on the server
    //variable imgControl contains the HTML structure in which the Image is rendered.
    //Then using for loop, I Replace the text "||FILENAME||" with the actual Image File Name and finally Append it to the div#dropzone
    function GetFileDetails() {
        var options = {};
        options.type = "POST",//Post Method
        options.url = 'Default.aspx/GetFileList',//URL  
        options.data = '{}',
        options.async = false,//synchronous Call  
        options.contentType = "application/json; charset=utf-8",
        options.dataType = "json",
        options.complete = function (response) { //callback function on completion 
            var resp = JSON.parse(response.responseText);
            var filesList = JSON.parse(resp.d);
            var imageControlList = '';
            for (var i = 0; i < filesList.length; i++) {
                imageControlList += imgControl.replace('||FILENAME||', filesList[i].File).replace('||FILENAME||', filesList[i].File);
            }
            $('#dropzone').html(imageControlList);
        };
        $.ajax(options);

    }

    //the function deleteImage is used to delete images
    function deleteImage(fileName) {
        ShowPopup();
        var options = {};
        options.type = "POST",
        options.url = 'Default.aspx/DeleteImage',
        options.data = '{ fileName :"' + fileName + '" }',
        options.async = false,
        options.contentType = "application/json; charset=utf-8",
        options.dataType = "json",
        options.complete = function (response) {
            GetFileDetails();
        };
        $.ajax(options);

        HidePopup();
    }

身体:

    <div id="MSG">
        <img src="loading.gif" alt="Uploading File" />
    </div>
    <div id="dropzone">

    </div>

CS文件中的两个Web方法:

[WebMethod]

public static string GetFileList()
{
    try
    {
        //This function is used to collect list of Files Names from the Images folder.
        //This function returns the data in JSON format
        //I am using a function called ConvertDataTabletoString to serialize a Datatable into a JSON String
        CommonFunction com = new CommonFunction();
        string[] filePaths = Directory.GetFiles(HttpContext.Current.Server.MapPath("Images/Stories/" + DateTime.Now.ToString("ddMMyyyy") + "/"));
        DataTable dt = new DataTable();
        dt.Columns.Add("File");
        foreach (string file in filePaths)
        {
            dt.Rows.Add(Path.GetFileName(file));
        }
        return com.ConvertDataTabletoString(dt);
    }
    catch (DirectoryNotFoundException direx)
    {
        throw direx;
    }
    catch (Exception ex)
    {
        throw ex;
    }
}
[WebMethod]

public static string DeleteImage(string fileName)
{
    //This function is used to delete a particular Image with the help of the Unique FileName
    try
    {
        File.Delete(HttpContext.Current.Server.MapPath("Images/Stories/" + DateTime.Now.ToString("ddMMyyyy") + "/") + fileName);
        return "Success";
    }
    catch (Exception)
    {
        return "Failed";
    }
}

Handler(ashx文件)名为FileUploader.ashx

public void ProcessRequest(HttpContext context)
  {
     try
        {
            if (context.Request.Files.Count > 0)
            {
                string FileName = "";
                string userId = "";
                CommonFunction comFun = new CommonFunction();
                HttpFileCollection files = context.Request.Files;
                for (int i = 0; i < files.Count; i++)
                {
                    HttpPostedFile file = files[i];
                   // Guid id = Guid.NewGuid();
                    userId = "XYZ";
                    if (userId == "")
                    {
                        userId = "Anonymus";
                    }
                    FileName = userId + "_" + file.FileName;
                    string dirName =     context.Server.MapPath("Images/Stories/" + DateTime.Now.ToString("ddMMyyyy")     + "/");
                    if (!Directory.Exists(dirName))
                    {
                        Directory.CreateDirectory(dirName);
                    }
                    string fName = (dirName + FileName);
                    file.SaveAs(fName);
                }
                context.Response.ContentType = "text/plain";
                context.Response.Write("Success");
            }
        }
        catch (Exception ex)
        {
            context.Response.ContentType = "text/plain";
            context.Response.Write(ex.Message);
        }
  }
  public bool IsReusable
    {
        get
        {
            return false;
        }
    }

一个名为CommonFunction.cs的App_Code类:

public CommonFunction()
        {
            //
            // TODO: Add constructor logic here
            //
        }

    public string ConvertDataTabletoString(DataTable dt)
    {
        System.Web.Script.Serialization.JavaScriptSerializer serializer = new System.Web.Script.Serialization.JavaScriptSerializer();
        List<Dictionary<string, object>> rows = new List<Dictionary<string, object>>();
        Dictionary<string, object> row;
        foreach (DataRow dr in dt.Rows)
        {
            row = new Dictionary<string, object>();
            foreach (DataColumn col in dt.Columns)
            {
                row.Add(col.ColumnName, dr[col]);
            }
            rows.Add(row);
        }
        return serializer.Serialize(rows);

    }

0 个答案:

没有答案