[MVC]檔案上傳-ajax

  • 4437
  • 0
  • MVC
  • 2017-01-12

檔案上傳-ajax

網頁

<!DOCTYPE html>

<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>UploadByAjax</title>
    <script src="~/Scripts/jquery-2.2.1.js"></script>
</head>
<body>
    <div>
        <input type="file" name="UploadFile" id="upload" multiple/>        
    </div>  

    <script>
        $(document).ready(function () {
            $('#upload').on('change', function (e) {
                //取得檔案
                var files = e.target.files;
                if (files.length > 0) {
                    if (window.FormData !== undefined) {
                        var data = new FormData();

                        //可上傳多檔案
                        for (var x = 0; x < files.length; x++) {
                            data.append(files[x].name, files[x]);
                        }

                        $.ajax({
                            type: "POST",
                            url: '@Url.Action("UploadByAjax", "FileUpload")',
                            contentType: false,
                            processData: false,
                            data: data,
                            success: function (result) {
                                console.log(result);
                            },
                            error: function (xhr, status) {                                
                                console.log("上傳失敗");
                            }
                        });
                    } else {
                        alert("此瀏覽器不支援HTML5檔案上傳");
                    }
                }
            });
        });
    </script>
</body>
</html>

Action

取得檔案的方式比較特別,是使用Controller底下的 Request物件來取得。

[HttpPost]
public JsonResult UploadByAjax()
{            
    //取得目前 HTTP 要求的 HttpRequestBase 物件
    foreach (string file in Request.Files)
    {
        var fileContent = Request.Files[file];
        if (fileContent != null && fileContent.ContentLength > 0)
        {
            // 取得的檔案是stream
            var stream = fileContent.InputStream;                    
            var fileName = Path.GetFileName(file);
            var path = Path.Combine(Server.MapPath("~/Files/"), fileName);
            using (var fileStream = System.IO.File.Create(path))
            {
                stream.CopyTo(fileStream);
            }
        }
    }

    return Json("Successed");
}

 

參考:

https://cmatskas.com/upload-files-in-asp-net-mvc-with-javascript-and-c/

http://stackoverflow.com/questions/19042116/ajax-beginform-in-mvc-to-upload-files

https://www.new-bamboo.co.uk/blog/2012/01/10/ridiculously-simple-ajax-uploads-with-formdata/

 

 

一天一分享,身體好健康。

該追究的不是過去的原因,而是現在的目的。