【轉】利用Ajax.BeginForm提交檔案

來源:互聯網
上載者:User

標籤:des   style   blog   http   io   ar   color   os   sp   

Ajax.BeginForm

 @using (Ajax.BeginForm("YourAction", "YourController", new AjaxOptions() { HttpMethod = "POST" }, new { enctype = "multipart/form-data"})){    @Html.AntiForgeryToken()    <input type="file" name="files"><br>    <input type="submit" value="Upload File to Server">}

Action Method

    [HttpPost]    [ValidateAntiForgeryToken]    public void YourAction(IEnumerable<HttpPostedFileBase> files)    {        if (files != null)        {            foreach (var file in files)            {                // Verify that the user selected a file                if (file != null && file.ContentLength > 0)                {                    // extract only the fielname                    var fileName = Path.GetFileName(file.FileName);                    // TODO: need to define destination                    var path = Path.Combine(Server.MapPath("~/Upload"), fileName);                    file.SaveAs(path);                }            }        }    }

【引者注.有時加入 [ValidateAntiForgeryToken]註解會出錯,具體原因不明,可刪除這行注釋】

Progress Bar

<div class="progress progress-striped">        <div class="progress-bar progress-bar-success">0%</div>    </div><div id="status"></div>

Jquery & Form script

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7/jquery.js"></script><script src="http://malsup.github.com/jquery.form.js"></script><script>(function() {var bar = $(‘.progress-bar‘);var percent = $(‘.progress-bar‘);var status = $(‘#status‘);$(‘form‘).ajaxForm({    beforeSend: function() {        status.empty();        var percentVal = ‘0%‘;        bar.width(percentVal)        percent.html(percentVal);    },    uploadProgress: function(event, position, total, percentComplete) {        var percentVal = percentComplete + ‘%‘;        bar.width(percentVal)        percent.html(percentVal);    },    success: function() {        var percentVal = ‘100%‘;        bar.width(percentVal)        percent.html(percentVal);    },    complete: function(xhr) {        status.html(xhr.responseText);    }}); })();       </script>

 

【轉】利用Ajax.BeginForm提交檔案

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.