[asp.net-mvc]文件上传保存空文件

标签: Asp.net-MVC C#
发布时间: 2016/10/9 5:56:15
注意事项: 本文中文内容可能为机器翻译,如要查看英文原文请点击上面连接.

我写文件上传模块在 c# 中使用 ajax 和 jQuery 在 ASP.NET MVC 5

我试着为后端代码 msdn 示例

    [HttpPost]
    public ActionResult Upload()
    {
        if (Request.Files.Count != 0)
        {
            for (int i = 0; i < Request.Files.Count; i++)
            {
                var file = Request.Files[i];
                var fileName = Path.GetFileName(file.FileName);
                var path = Path.Combine(Server.MapPath("~/Junk/"), fileName);
                file.SaveAs(path);
            }
        }

        return new EmptyResult();
    }

问题是,此方法创建空文件 (大小为 0 字节)。这是因为我们不读取输入流,我们只能读文件名为例吧

如何使这项工作?

更新 1 (已过帐的 js 代码)︰

<script type="text/javascript">
    $(document).ready(function () {
        $("#Upload").click(function () {
            var formData = new FormData();
            var totalFiles = document.getElementById("FileUpload").files.length;
            for (var i = 0; i < totalFiles; i++) {
                var file = document.getElementById("FileUpload").files[i];

                formData.append("FileUpload", file);
            }
            $.ajax({
                type: "POST",
                url: '/Home/Upload',
                data: formData,
                dataType: 'json',
                contentType: false,
                processData: false,
                //beforeSend: beforeSendHandler,
                success: function(){
                    alert("CAT");
                },
                //error: errorHandler,
                // Form data
                data: formData,
                //Options to tell jQuery not to process data or worry about content-type.
                cache: false,
                contentType: false,
                processData: false
            });
            ajaxRequest.done(function () {
                alert("CAAT");
            });
        });
    });

</script>

更新 2 (添加 html 标记)︰

<div class="container body-content">
        <hr />
        <input type="file" id="FileUpload" multiple />
        <input type="button" id="Upload" value="Upload" />
        <hr />
        <footer>
       ...
        </footer>
    </div>

解决方法 1:

你几乎有与您当前的代码。

我读过关于这一对︰ https://cmatskas.com/upload-files-in-asp-net-mvc-with-javascript-and-c/和适应我的答案。

试试这个︰

你上传的部分︰

// The same as you already have,  but your button as a "button"
<div ...>

    <input type="file" id="FileUpload" multiple />
    <button type="button" id="Upload" value="Upload" />
    ...
</div>

你的 jQuery:

<script type="text/javascript">
    $(document).ready(function () {
        $("#Upload").click(function () {
            var files = $("FileUpload").target.files;
            if (files.Length > 0)
            {
                // Check if the browser supports FormData
                if (window.FormData !== undefined) {
                    var formData = new FormData();
                    // Add the files 
                    for (var x = 0; x < files.length; x++){
                        data.append("file" + x, files[x]);
                    }

                    $.ajax({
                        type: "POST",
                        url: 'Home/Upload?id=someId'
                        data: formData,
                        dataType: 'json',
                        contentType: false,
                        processData: false,
                        //beforeSend: beforeSendHandler,
                        success: function(){
                            alert("CAT");
                        },
                        //error: errorHandler,
                        // Form data
                        data: formData,
                        //Options to tell jQuery not to process data or worry about content-type.
                        cache: false,
                        contentType: false,
                        processData: false
                    });
                    ajaxRequest.done(function () {
                        alert("CAAT");
                    });
                }
                else {
                    // If the browser does not support FormData, show an alert
                    alert("Your browser does not support this type of upload");
                }
            }); 
        }
    });
</script>

您的控制器︰

[HttpPost]
public ActionResult Upload(string id)
{
    try
    {
        foreach (string file in Request.Files)
        {
            var fileContent = Request.Files[file];
            if (fileContent != null && fileContent.ContentLength > 0)
            { 
                // get a stream
                var stream = fileContent.InputStream;
               // and write the file to disk
               var fileName = Path.GetFileName(file); 
               var path = Path.Combine(Server.MapPath("~/Junk"), fileName); 
               using (var fileStream = File.Create(path))
               {
                   stream.CopyTo(fileStream);
               }
           }
        }
    }
    catch (Exception)
    {
        Response.StatusCode = (int)HttpStatusCode.BadRequest;
        return Json("Upload failed");
    }

    return Json("Upload succeeded");
}

请注意您可能想要更改一两件事情,但这应该是你需要的很多。

希望这有助于 !

官方微信
官方QQ群
31647020