文件API文件上载 - 在ASP.NET MVC中读取XMLHttpRequest

时间:2011-03-03 14:09:33

标签: jquery asp.net-mvc file-upload

我正在尝试在ASP.NET MVC中实现Gmail样式拖放文件上传。

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

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

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中 - 它是参数吗?如果是这样,我应该期待什么类型&如何从中提取字节数组并从中提取上传的文件信息?

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

任何建议都将不胜感激!

2 个答案:

答案 0 :(得分:38)

想出来。这是C#代码:

[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代码:

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

答案 1 :(得分:0)

这很棒。略有改进:

Java