文件上传保存空文件

时间:2016-07-13 10:23:57

标签: c# asp.net-mvc

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

我为后端代码

尝试了msdn示例
<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>

问题是此方法创建空文件(大小为0字节)。我想这是因为我们没有读取输入流,我们只是在示例中读取文件名。

如何使这项工作?

更新1(已发布js代码):

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

更新2(添加了html-markup):

containerViewWillLayoutSubviews()

3 个答案:

答案 0 :(得分: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");
}

请注意你可能想要改变一些事情,但这应该是你需要的。

希望这有帮助!

答案 1 :(得分:0)

[HttpPost]
public ActionResult Upload(HttpPostedFileBase file)
{
var Image = Path.GetFileName(file.FileName);
string path = Path.Combine(Server.MapPath("~/images/Attachment"), Image);
file.SaveAs(path);
}

并在视图部分

@using (Html.BeginForm("Upload", "ControllerName", FormMethod.Post, new { enctype = "multipart/form-data" }))
{

<input type="file" name="file"/>
<button type="submit" Submit</button>
}

我希望这会有所帮助

答案 2 :(得分:0)

可能的方法:

 <form id="form1">
      <input accept="image/*" type="file" id="txtFileInpu" />
      <input type="submit" value="Upload" />
      </form>

JS

 <script type="text/javascript">
        var form = document.getElementById('form1').onsubmit = function (e) {
            e.preventDefault();

            var formdata = new FormData(); 
            var fileInput = document.getElementById('txtFileInput');
            if (fileInput != "" && fileInput.files.length > 0) {
                for (i = 0; i < fileInput.files.length; i++) {
                    formdata.append(fileInput.files[i].name, fileInput.files[i]);
                }
                var xhr = new XMLHttpRequest();
                xhr.open('POST', '/Controller/Upload');
                xhr.send(formdata);
                xhr.onreadystatechange = function () {
                    if (xhr.readyState == 4 && xhr.status == 200) {
                        var result = xhr.responseText;
                        if(result=="Uploaded")
                              //file uploaded
                         else
                             //file not uploaded
                    }
                }
                return false;
            }
        }

    </script>

C#

public string Upload()
    {
        try
        {
             for (int i = 0; i < Request.Files.Count; i++)
            {
                HttpPostedFileBase file = Request.Files[i];

                string strTargetFolder = Server.MapPath("~/Junk");

                if (!Directory.Exists(strTargetFolder))
                {
                    Directory.CreateDirectory(strTargetFolder);
                }

                string targetPath = Path.Combine(strTargetFolder, file.FileName);
                file.SaveAs(targetPath);

            }
            return "Uploaded";
        }
        catch (Exception exp)
        {
            return "ERROR";
        }


}