使用dropzon.js上传文件

时间:2015-04-28 09:07:41

标签: asp.net-mvc-4 razor dropzone.js

我正在尝试使用dropzone.js上传文件

查看:

 insert into tick_audit (user_account, client_id, date_time, table_name, table_record_id, descr, remote_ip_address)
 values (@UserId, @ClientId, getdate(), @Table, @TableRecord, @Descr, @RemoteIP)

JS:

@using (Html.BeginForm("SaveMethod", "ControllerName", FormMethod.Post, new { enctype = "multipart/form-data", @class = "dropzone", id = "js-upload-form" }))
........................
 <div class="form-inline">
                <div class="form-group">
                    <input type="file" name="MainFile" id="js-upload-files"/>                    
                </div>
                <div class="upload-drop-zone" id="drop-zone">
                    Just drag and drop files here
                </div>
                <div class="dropzone-previews"></div>
</div>

控制器:

 var formData = null;
  formData = new FormData($form[0]);

  dropZone.ondrop = function (e) {
            e.preventDefault();
            this.className = 'upload-drop-zone';

            startUpload(e.dataTransfer.files)
        }

        dropZone.ondragover = function () {
            this.className = 'upload-drop-zone drop';
            return false;
        }

        dropZone.ondragleave = function () {
            this.className = 'upload-drop-zone';
            return false;
        }   
       var startUpload = function (files) {            
        for (var i = 0; i < files.length; i++) {
            formData.append(files[i].name, files[i]);
        }            
    }

现在,提交后,我希望删除丢弃区域中的文件以及上传控件中附加的文件。在这里,会发生什么是文件给我null,当我使用Request.Files [“MainFile”]我只得到dropzone区域上删除的文件,它没有显示我上传到的文件控制。

我无法找到问题所在。任何帮助都非常感谢。

1 个答案:

答案 0 :(得分:0)

使用Dropzone JS和HTML5在ASP.NET MVC中上传文件

您可以从官方网站http://www.dropzonejs.com/下载最新版本,也可以通过以下命令使用nuget包管理控制台安装程序包管理器控制台

PM> Install-Package dropzone

enter image description here

现在在BundleConfig.cs中为您的脚本文件创建一个包

bundles.Add(new ScriptBundle("~/bundles/dropzonescripts").Include(
                     "~/Scripts/dropzone/dropzone.js"));

同样在BundleConfig.cs中添加dropzone样式表

bundles.Add(new StyleBundle("~/Content/dropzonescss").Include(
                     "~/Scripts/dropzone/css/basic.css",
                     "~/Scripts/dropzone/css/dropzone.css"));

现在在_Layout页面中添加捆绑引用 enter image description here

查看页面

<div class="jumbotron">
    <form action="~/Home/SaveUploadedFile" method="post" enctype="multipart/form-data" class="dropzone" id="dropzoneForm" style="width: 50px; background: none; border: none;">
        <div class="fallback">
            <input name="file" type="file" multiple />
            <input type="submit" value="Upload" />
        </div>
    </form>
</div>

<强>控制器:

public ActionResult SaveUploadedFile()
{
        bool isSavedSuccessfully = true;
        string fName = "";
                try{
        foreach (string fileName in Request.Files)
        {
            HttpPostedFileBase file = Request.Files[fileName];
            //Save file content goes here
            fName = file.FileName;
            if (file != null && file.ContentLength > 0)
            {

                var originalDirectory = new DirectoryInfo(string.Format("{0}Images\\WallImages", Server.MapPath(@"\")));

                string pathString = System.IO.Path.Combine(originalDirectory.ToString(), "imagepath");

                var fileName1 = Path.GetFileName(file.FileName);

                bool isExists = System.IO.Directory.Exists(pathString);

                if (!isExists)
                    System.IO.Directory.CreateDirectory(pathString);

                var path = string.Format("{0}\\{1}", pathString, file.FileName);
                file.SaveAs(path);

            }

        } 

       }
       catch(Exception ex)
        {
            isSavedSuccessfully = false;
        }


        if (isSavedSuccessfully)
        {
            return Json(new { Message = fName });
        }
        else
        {
            return Json(new { Message = "Error in saving file" });
        }
 }

现在将以下脚本添加到脚本标记中的视图页面。

//File Upload response from the server
        Dropzone.options.dropzoneForm = {
            init: function () {
                this.on("complete", function (data) {
                    //var res = eval('(' + data.xhr.responseText + ')');
                     var res = JSON.parse(data.xhr.responseText);
                });
            }

        };

在这里,您可以看到服务器的响应。