Drag and drop files in mvc

2020-02-12 11:49发布

问题:

I want to upload file using drag and drop. I have written code as below but every time I attempt to upload a file, it is showing upload failed. Can anyone tell me where I am wrong? I want to drag items from outer source and have it uploaded into my folder but I am not able to do it.

For controller :-

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();
   }
}

and for view it is :-

<!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>

回答1:

Your HandleFileUpload action is private! In ASP.NET MVC controller actions need to be public. Also I would recommend you wrapping IDisposable resources in using statements to avoid leaking handles:

[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 });
}


回答2:

First I have tried the solution suggested by Darin Dimitrov and it did not work, but then I debug it, realized that it has server error 500, then I inspect the code realize that I don't have upload folder...so causing the issue.

so just create the folder you will be fine