【问题标题】:Drag and drop files in mvc在mvc中拖放文件
【发布时间】:2013-01-28 07:07:10
【问题描述】:

我想通过拖放上传文件。我编写了如下代码,但每次尝试上传文件时,都显示上传失败。谁能告诉我我错在哪里?我想从外部源中拖动项目并将其上传到我的文件夹中,但我无法做到。

对于控制器:-

public ActionResult File()
{
   return View();
}

/// <summary>
/// The max file size in bytes
/// </summary>
protected int maxRequestLength
{
   get
   {
      HttpRuntimeSection section =
         ConfigurationManager.GetSection("system.web/httpRuntime") as HttpRuntimeSection;

      if (section != null)
         return section.MaxRequestLength * 1024; // Default Value
      else
         return 4096 * 1024; // Default Value
   }
}

/// <summary>
/// Checks if a file is sent to the server
/// and saves it to the Uploads folder.
/// </summary>
[HttpPost]
private void handleFileUpload()
{
   if (!string.IsNullOrEmpty(Request.Headers["X-File-Name"]))
   {
      string path = Server.MapPath(string.Format("~/Uploads/{0}", Request.Headers["X-File-Name"]));
      Stream inputStream = Request.InputStream;

      FileStream fileStream = new FileStream(path, FileMode.OpenOrCreate);

      inputStream.CopyTo(fileStream);
      fileStream.Close();
   }
}

为了查看它是:-

<!DOCTYPE html>

<html>
<head runat="server">
    <title>Drag n' Drop File Upload</title>
    <link href="/Style.css" rel="Stylesheet" />
    <style>
body
{
    font: 12px Arial;
}

#dropZone
{
    border-radius: 5px;
    border: 2px solid #ccc;
    background-color: #eee;
    width: 250px;
    padding: 50px 0;
    text-align: center;
    font-size: 18px;
    color: #555;
    margin: 50px auto;
}

#dropZone.hover
{
    border-color: #aaa;
    background-color: #ddd;
}

#dropZone.error
{
    border-color: #f00;
    background-color: #faa;
} 
    </style>
    <script src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.6.1.min.js"></script>

    <script type="text/javascript">
        var dropZone;

        // Initializes the dropZone
        $(document).ready(function () {
            dropZone = $('#dropZone');
            dropZone.removeClass('error');

            // Check if window.FileReader exists to make 
            // sure the browser supports file uploads
            if (typeof(window.FileReader) == 'undefined') {
                dropZone.text('Browser Not Supported!');
                dropZone.addClass('error');
                return;
            }

            // Add a nice drag effect
            dropZone[0].ondragover = function () {
                dropZone.addClass('hover');
                return false;
            };

            // Remove the drag effect when stopping our drag
            dropZone[0].ondragend = function () {
                dropZone.removeClass('hover');
                return false;
            };

            // The drop event handles the file sending
            dropZone[0].ondrop = function(event) {
                // Stop the browser from opening the file in the window
                event.preventDefault();
                dropZone.removeClass('hover');

                // Get the file and the file reader
                var file = event.dataTransfer.files[0];

               @* if(file.size > @maxRequestLength {
                            dropZone.text('File Too Large!');
                        dropZone.addClass('error');
                        return false;*@
            //    // Validate file size
            //    if(file.size > <%=maxRequestLength%>) {
            //        dropZone.text('File Too Large!');
            //    dropZone.addClass('error');
            //    return false;
            //}

            // Send the file
            var xhr = new XMLHttpRequest();
        //    xhr.upload.addEventListener('progress', uploadProgress, false);
            xhr.onreadystatechange = stateChange;
            xhr.open('POST', 'Home/handleFileUpload', true);
            xhr.setRequestHeader('X-FILE-NAME', file.name);
            xhr.send(file);
        };
        });

        // Show the upload progress
        function uploadProgress(event) {
            var percent = parseInt(event.loaded / event.total * 100);
            $('#dropZone').text('Uploading: ' + percent + '%');
        }

        // Show upload complete or upload failed depending on result
        function stateChange(event) {
            if (event.target.readyState == 4) {
                if (event.target.status == 200) {
                    $('#dropZone').text('Upload Complete!');
                }
                else {
                    dropZone.text('Upload Failed!');
                    dropZone.addClass('error');
                }
            }
        }
        //window.onload = fun;
        //function fun() {
        //    $.post("Home/handleFileUpload", {}, function (response) {
        //        alert("hi");
        //    })



    </script>
</head>
<body>
    <form id="form1" runat="server">
    <div id="dropZone">
        Drop File Here to Upload.
    </div>
    </form>
</body>
</html>

【问题讨论】:

    标签: asp.net-mvc asp.net-mvc-3 html file drag-and-drop


    【解决方案1】:

    您的HandleFileUpload 操作是私密!在 ASP.NET MVC 中,控制器操作需要是公共的。另外,我建议您将 IDisposable 资源包装在 using 语句中以避免泄漏句柄:

    [HttpPost]
    public ActionResult HandleFileUpload()
    {
        if (!string.IsNullOrEmpty(Request.Headers["X-File-Name"]))
        {
            string path = Server.MapPath(string.Format("~/Uploads/{0}", Request.Headers["X-File-Name"]));
            using (var fileStream = new FileStream(path, FileMode.OpenOrCreate))
            {
                Request.InputStream.CopyTo(fileStream);
            }
            return Json(new { success = true });
        }
    
        return Json(new { success = false });
    }
    

    【讨论】:

    • 我已将其公开,但仍无法正常工作..您可以将此代码粘贴到您的 VS 并运行它,然后告诉我哪里错了吗?
    • 我确实做到了。复制粘贴您的代码,将操作公开,并且效果非常好。确保您已在服务器上创建了一个~/Uploads 文件夹。还要确保您使用的是支持 HTML5 文件 API 的浏览器,例如 Google Chrome。这不适用于 Internet Explorer 9 或更低版本。
    • 我确实有那个文件夹,但是每当我将文件拖入其中时,它显示上传失败...为什么它在我的电脑上不起作用?您对我的代码进行了任何更改吗?为什么你返回json?请在此处处理并粘贴您的工作代码
    • 当我使用 webforms 执行此代码时,它可以正常工作,但不能在 mvc 中工作
    • 我所做的只是创建一个新的 ASP.NET MVC 应用程序,创建一个新的 Uploads 文件夹,按照我的答案所示进行控制器操作,并且它起作用了。此外,我还在视图顶部放置了一个@{ Layout = null; },以确保不会为该特定视图加载 _Layout 文件。至于我返回 JSON 的原因,我这样做是为了向客户端指示操作是成功还是失败。
    【解决方案2】:

    首先我尝试了 Darin Dimitrov 建议的解决方案,但它没有用,但后来我调试它,意识到它有服务器错误 500,然后我检查代码发现我没有上传文件夹......所以导致了这个问题。

    所以只要创建文件夹就可以了

    【讨论】:

      猜你喜欢
      • 2021-12-24
      • 1970-01-01
      • 1970-01-01
      • 2019-03-18
      • 2016-07-17
      • 1970-01-01
      • 1970-01-01
      • 2018-01-26
      • 1970-01-01
      相关资源
      最近更新 更多