文件 API 文件上传 - 在 ASP.NET MVC 中读取 XMLHttpRequest [英] File API File Upload - Read XMLHttpRequest in ASP.NET MVC

查看:16
本文介绍了文件 API 文件上传 - 在 ASP.NET MVC 中读取 XMLHttpRequest的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在 ASP.NET MVC 中实现 Gmail 风格的拖放文件上传.

I am trying to implement Gmail style drag-and-drop file upload in ASP.NET MVC.

我一直在关注这篇文章:http://robertnyman.com/html5/fileapi-upload/fileapi-upload.html 并希望将上传的文件发布到 MVC 控制器操作.

I have been following this article: http://robertnyman.com/html5/fileapi-upload/fileapi-upload.html and want to post uploaded files to an MVC controller action.

为此,我修改了链接中的示例 JavaScript 脚本以指向我的控制器操作:

To do this, I modified the sample JavaScript script in the link to point to my controller action:

xhr.open("post", "/home/UploadFiles", true);

这是我的控制器操作:

[HttpPost]
public virtual string UploadFiles(object obj)
{
    var length = Request.ContentLength;
    var bytes = new byte[length];
    Request.InputStream.Read(bytes, 0, length);
    // var bytes has byte content here. what do do next?

    return "Files uploaded!";
}

我设置了一个断点,当我上传文件时,断点被命中 - 这很好.但是如何从上传的 (javascript) XMLHttpRequest 对象中提取数据?我不认为它在 HttpRequest 中 - 它是参数吗?如果是这样,我应该期待什么类型&如何提取字节数组并从中提取上传的文件信息?

I set a breakpoint, and when I upload a file, the breakpoint gets hit - which is good. But how do I extract the data from the uploaded (javascript) XMLHttpRequest object? I don't think its in the HttpRequest - is it the parameter? If so, what type should i expect & how do I extract the byte array and extract the uploaded file info from it?

(我正在使用 Chrome - 我知道它在 IE 中不起作用)

(I am using Chrome - I know it doesn't work in IE)

任何建议将不胜感激!

推荐答案

想通了.这是 C# 代码:

Figured it out. Here is the C# code:

[HttpPost]
    public virtual string UploadFiles(object obj)
    {
        var length = Request.ContentLength;
        var bytes = new byte[length];
        Request.InputStream.Read(bytes, 0, length);
        // bytes has byte content here. what do do next?

        var fileName = Request.Headers["X-File-Name"];
        var fileSize = Request.Headers["X-File-Size"];
        var fileType = Request.Headers["X-File-Type"];

        var saveToFileLoc = string.Format("{0}\{1}",
                                       Server.MapPath("/Files"),
                                       fileName);

        // save the file.
        var fileStream = new FileStream(saveToFileLoc, FileMode.Create, FileAccess.ReadWrite);
        fileStream.Write(bytes, 0, length);
        fileStream.Close();

        return string.Format("{0} bytes uploaded", bytes.Length);
    }

这是 Javascript 代码:

And here's the Javascript code:

<script type="text/javascript">
(function ()
{
    var filesUpload = document.getElementById("files-upload");
    var dropArea = document.getElementById("drop-area");
    var fileList = document.getElementById("file-list");

    function uploadFile(file)
    {
        var li = document.createElement("li");
        var progressBarContainer = document.createElement("div");
        var progressBar = document.createElement("div");

        progressBarContainer.className = "progress-bar-container";
        progressBar.className = "progress-bar";
        progressBarContainer.appendChild(progressBar);
        li.appendChild(progressBarContainer);

        // Uploading - for Firefox, Google Chrome and Safari
        var xhr = new XMLHttpRequest();

        // Update progress bar
        xhr.upload.addEventListener("progress", function (evt)
        {
            if (evt.lengthComputable)
            {
                progressBar.style.width = (evt.loaded / evt.total) * 100 + "%";
            }
        }, false);

        // File uploaded
        xhr.addEventListener("load", function ()
        {
            progressBarContainer.className += " uploaded";
            progressBar.innerHTML = "Uploaded!";
        }, false);

        xhr.open("post", "/home/UploadFile", true);

        // Set appropriate headers
        xhr.setRequestHeader("Content-Type", "multipart/form-data");
        xhr.setRequestHeader("X-File-Name", file.fileName);
        xhr.setRequestHeader("X-File-Size", file.fileSize);
        xhr.setRequestHeader("X-File-Type", file.type);

        // Send the file
        xhr.send(file);

        // Present file info and append it to the list of files
        var div = document.createElement("div");
        li.appendChild(div);
        var fileInfo = "<div><strong>Name:</strong> " + file.name + "</div>";
        fileInfo += "<div><strong>Size:</strong> " + parseInt(file.size / 1024, 10) + " kb</div>";
        fileInfo += "<div><strong>Type:</strong> " + file.type + "</div>";
        div.innerHTML = fileInfo;

        // insert at beginning of list.
        fileList.insertBefore(li, fileList.firstChild);

        // or insert at end of list.
        //fileList.appendChild(li);
    }

    function traverseFiles(files)
    {
        if (typeof files !== "undefined")
        {
            for (var i = 0, l = files.length; i < l; i++)
            {
                uploadFile(files[i]);
            }
        }
        else
        {
            fileList.innerHTML = "No support for the File API in this web browser";
        }
    }

    filesUpload.addEventListener("change", function ()
    {
        traverseFiles(this.files);
    }, false);

    dropArea.addEventListener("dragleave", function (evt)
    {
        var target = evt.target;

        if (target && target === dropArea)
        {
            this.className = "";
        }
        evt.preventDefault();
        evt.stopPropagation();
    }, false);

    dropArea.addEventListener("dragenter", function (evt)
    {
        this.className = "over";
        evt.preventDefault();
        evt.stopPropagation();
    }, false);

    dropArea.addEventListener("dragover", function (evt)
    {
        evt.preventDefault();
        evt.stopPropagation();
    }, false);

    dropArea.addEventListener("drop", function (evt)
    {
        //document.getElementById("file-list").innerHTML = "";

        traverseFiles(evt.dataTransfer.files);
        this.className = "";
        evt.preventDefault();
        evt.stopPropagation();
    }, false);
})();

这篇关于文件 API 文件上传 - 在 ASP.NET MVC 中读取 XMLHttpRequest的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆