This is a migrated thread and some comments may be shown as answers.

[Solved] Create Standalone Image Browser

0 Answers 16 Views
General Discussions
This is a migrated thread and some comments may be shown as answers.
This question is locked. New answers and comments are not allowed.
Duke
Top achievements
Rank 1
Duke asked on 07 Mar 2013, 08:13 PM
I search for this and get no good result. Hence, I spend some time to create one in my project. Hope it helps.
It's based on the demo of ImageBrowser here.

Additional information: Base EditorFileBrowserController only allows image files. So if you want to upload
other than images, you need to override the upload method, I think.


May God Bless.

ImageBrowserController.cs:
using gifttechLib.Misc;
using gifttechLib.Parameter;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Telerik.Web.Mvc.UI;
 
namespace gifttech.Controllers
{
    public class ImageBrowserController : EditorFileBrowserController
    {
 
        /// <summary>
        /// Gets the base paths from which content will be served.
        /// </summary>
        public override string[] ContentPaths
        {
            get
            {
                return new[] { CreateUserFolder() };
            }
        }
 
        private string UserID
        {
            get
            {
                UserSession us = Tools.GetUserSession(HttpContext);
                if (us == null)
                {
                    return null;
                }
                return Tools.AccountIdWarpper(GlobalPara.IMG_FOLDER_PREFIX, us.Id, 10);
            }
        }
 
        private string CreateUserFolder()
        {
            var userFolder = Path.Combine(GlobalPara.IMG_FOLDER_USR, UserID);
            var virtualPath = Path.Combine(ConfigurationManager.AppSettings["FileUploadPath"], userFolder);
            var path = Server.MapPath(virtualPath);
            if (!Directory.Exists(path))
            {
                Directory.CreateDirectory(path);
            }
            return virtualPath;
        }
 
        public override ActionResult Upload(string path, HttpPostedFileBase file)
        {
            #region Image File Validation
            string fileName = file.FileName.ToLower();
            string fileExt = fileName.Substring(fileName.LastIndexOf("."), 4);
            if (!ConfigurationManager.AppSettings["ImageFileExtension"].Contains(fileExt))
            {
                Dictionary<string, object> dict = new Dictionary<string, object>();
                dict.Add("error", true);
                dict.Add("message", string.Format(Resource.ValidateImageFileExtensionMsg, ConfigurationManager.AppSettings["ImageFileExtension"].ToUpper()));
                return Json(dict);
            }
            #endregion
 
            #region File Name Validation
            string destPath = Server.MapPath(Path.Combine(ContentPaths[0], file.FileName));
            if (System.IO.File.Exists(destPath))
            {
                Dictionary<string, object> dict = new Dictionary<string, object>();
                dict.Add("error", true);
                dict.Add("message", Resource.ValidateFileExisted);
                return Json(dict);
            }
            #endregion
 
            #region Validate Space Size
            UserSession us = Tools.GetUserSession(HttpContext);
            DirectoryInfo info = new DirectoryInfo(Server.MapPath(ContentPaths[0]));
            long total = info.EnumerateFiles().Sum(f => f.Length);
            long limit = us.PersonalSpaceSize == 0 ? Int64.Parse(ConfigurationManager.AppSettings["PersonalFileSpace"]) : us.PersonalSpaceSize;
            if ((total + file.ContentLength) > limit)
            {
                Dictionary<string, object> dict = new Dictionary<string, object>();
                dict.Add("error", true);
                dict.Add("message", Resource.ValidateSpaceSize);
                return Json(dict);
            }
            #endregion
 
            return base.Upload(path, file);
        }
 
    }
}

View File:
@section styles{
    @(Html.Telerik().StyleSheetRegistrar().DefaultGroup(group => group
                                        .Add("telerik.common.css")
                                        .Add("telerik.telerik.min.css")
    ))
}
@section scripts{
    <script type="text/javascript" src="~/Scripts/jquery.form.js"></script>
    <script type="text/javascript" src="~/Scripts/GiftTechCommon.js"></script>
    <script type="text/javascript">
        // Create GiftTechObj and ModalDialog
        var subModalMsg = createModalAlertDialog('SubmitModalMsg');
        var gfAjax = new GfAjaxHandler(subModalMsg);
        var preSelected = null;
        var selected = null;
        var newNode = null;
        var path = "";
        var totalSize = 0;
 
        function selected(obj) {
            selected = obj;
        }
 
        function deleteItem() {
            if (selected != null && confirm('Are you sure to delete "' + select.attr('') + '"?'))
                alert('');
        }
 
        function createFileNode(data, type, path, newfile) {
            var li = $('<li class="t-tile" data-path="' + path + data.Name + '" data-name="' + data.Name + '" data-size="' + data.Size + '" data-kind="' + type + '"></li>');
            var div = $('<div class="t-thumb"></div>');
            var img;
            if (type == 'f') {
                if (newfile)
                    img = $('<img alt="ajax-loader-large.gif" style="width:80px;" src="/Content/gui/ajax-loader-large.gif" class="t-image" />');
                else
                    img = $('<img alt="' + data.Name + '" style="width:80px;" src="' + path + data.Name + '" class="t-image" />');
            }
            else if (type == 'd')
                img = $('<span class="t-icon t-folder"></span>');
 
            var name = $('<strong>' + data.Name + '</strong>');
            //var size = $('<span class="t-filesize">' + data.Size + ' bytes</span>');
 
            img.appendTo(div);
            div.appendTo(li);
            name.appendTo(li);
            //size.appendTo(li);
 
            li.click(function () {
                //$(this).siblings().removeClass("t-state-selected");
                if (preSelected)
                    preSelected.removeClass("t-state-selected");
 
                $(this).addClass("t-state-selected");
                $('#RemoveFile').removeClass('t-state-disabled');
                selected = $(this);
                preSelected = $(this);
            });
            li.appendTo($('#t-editor-image-list'));
            return li;
        }
 
        $(document).ready(function () {
            $("input:file").change(function () {
                var fileName = $(this).val();
                if ($.trim(fileName) != "") {
                    var file = fileName.substring(fileName.lastIndexOf('\\') + 1, fileName.length);
                    newNode = createFileNode({ Name: file }, 'f', path, true);
                    $('#upload').submit();
                }
                $(this).replaceWith($("input[type='file']").attr("name","file").clone(true));
            });
 
            // Ajax Upload
            $('#upload').ajaxForm({
                //iframe: true,
                dataType: 'json',
                //beforeSubmit: function (arr, $form, options) {
                //    gfAjax.dlg = subModalMsg;
                //},
                success: function (data) {
                    if (data.error) {
                        newNode.remove();
                        gfAjax.commonSuccessHandler(data, subModalMsg);
                    } else {
                        var img = newNode.find('img');
                        img.css('display', 'none');
                        img.attr("src", path + data.Name);
                        img.fadeIn('slow');
 
                        // Update the size
                        newNode.attr('data-size', data.Size);
                        totalSize += data.Size;
                        $('#SpaceUsed').text((totalSize / 1024 / 1024).toFixed(2) + " MB");
                    }
                },
                error: function (xhr, textStatus, errorThrown) {
                    newNode.remove();
                    gfAjax.commonErrorHandler(xhr, subModalMsg);
                }
            });
 
            $('#RemoveFile').click(function () {
                if (selected != null) {
                    if (confirm('Are your sure to remove "' + selected.attr('data-name') + '"?')) {
                        $.ajax({
                            type: "POST",
                            url: "/ImageBrowser/DeleteFile",
                            data: { path: selected.attr('data-path') },
                            success: function (data) {
                                totalSize -= selected.attr('data-size');
                                $('#SpaceUsed').text((totalSize / 1024 / 1024).toFixed(2) + " MB");
 
                                selected.remove();
                                selected = null;
                                $('#RemoveFile').addClass('t-state-disabled');
                            },
                            error: function (xhr, textStatus, errorThrown) {
                                gfAjax.commonErrorHandler(xhr, subModalMsg);
                            }
                        });
                    }
                }
            });
 
            $.ajax({
                type: "POST",
                url: "/ImageBrowser/Browse",
                success: function (data) {
                    path = data.Path;
                    $('#path').val(data.Path);
                    $.each(data.Files, function (index, value) {
                        createFileNode(value, 'f', data.Path);
                        totalSize += value.Size;
                    });
 
                    $('#SpaceUsed').text((totalSize / 1024 / 1024).toFixed(2) + " MB");
                }
            });
        });
    </script>
}
@Html.Partial("_GiftTechTitle")
@Html.Partial("_GiftTechBreadNavigation")
<div class="t-widget t-imagebrowser" style="display: block; border: none; margin-top: 10px;">
    <div class="t-window-content t-content" style="width: 750px; background: none;">
        <div class="t-editor-dialog" style="border: none; padding-top: 0px;">
            <div class="t-image-browser">
                <div class="t-widget t-toolbar t-floatwrap">
                    <div class="t-toolbar-wrap">
                        <div class="t-widget t-upload">
                            <div class="t-dropzone">
                                <form id="upload" method="post" enctype="multipart/form-data" action="/ImageBrowser/Upload">
                                    <div class="t-button t-button-icontext t-button-bare t-upload-button">
                                        <span class="t-icon t-add"></span>Upload<input type="file" name="file" />
                                    </div>
                                    <em>drop files here to upload</em>
                                    <input type="hidden" id="path" name="path" value="" />
                                </form>
                            </div>
                        </div>
                        <!--<button id="AddFolder" type="button" class="t-button t-button-icon t-button-bare"><span class="t-icon t-addfolder"></span></button>-->
                        <button id="RemoveFile" type="button" class="t-button t-button-icon t-button-bare t-state-disabled"><span class="t-icon t-delete"></span></button>
                          
                    </div>
                    <div class="t-tiles-arrange">Space Size: @(ViewBag.SpaceLimit) (<span id="SpaceUsed" style="color: cornflowerblue;"></span> Used) </div>
                </div>
                <ul id="t-editor-image-list" class="t-reset t-floats t-tiles">
                </ul>
            </div>
        </div>
    </div>
</div>

Tags
General Discussions
Asked by
Duke
Top achievements
Rank 1
Share this question
or