Kỷ thuật upload file dùng Ajax, Json và Jquery form trong ASP.Net MVC
Trước khi vào bài viết này tôi tin chắc rằng bạn đã có đầy đủ thư viện để thực hiện nó. Jquery.Form là plugin cho Jquery được phát triển từ Mike Alsup. bạn có thể download ở đây và xem thêm.
Trở lại với bài viết tôi bắt đầu tạo các page aspx và Controller cho ví dụ này. Trước tiên tôi config cho Web.Config giới hạn file mà tôi upload. Bạn thêm đoạn code sau vào cuối cùng của file web.config :
<!-- 100 MB max file upload limit for only the file upload controller action -->
<location path="Upload/AjaxUpload">
<system.web>
<httpruntime maxrequestlength="102400"></httpruntime>
</system.web>
</location>
Tại demo của bạn bạn thêm một folder là Helpers hoặc tạo ở đâu cũng được tùy bạn với file cs trong Helpers là FileUploadJsonResult và được thừa kế từ JsonResult. Code cho file này như sau :
///
/// A JsonResult with ContentType of text/html and the serialized object contained within textarea tags
///
/// A JsonResult with ContentType of text/html and the serialized object contained within textarea tags
///
///
/// It is not possible to upload files using the browser's XMLHttpRequest
/// object. So the jQuery Form Plugin uses a hidden iframe element. For a
/// JSON response, a ContentType of application/json will cause bad browser
/// behavior so the content-type must be text/html. Browsers can behave badly
/// if you return JSON with ContentType of text/html. So you must surround
/// the JSON in textarea tags. All this is handled nicely in the browser
/// by the jQuery Form Plugin. But we need to overide the default behavior
/// of the JsonResult class in order to achieve the desired
///
/// It is not possible to upload files using the browser's XMLHttpRequest
/// object. So the jQuery Form Plugin uses a hidden iframe element. For a
/// JSON response, a ContentType of application/json will cause bad browser
/// behavior so the content-type must be text/html. Browsers can behave badly
/// if you return JSON with ContentType of text/html. So you must surround
/// the JSON in textarea tags. All this is handled nicely in the browser
/// by the jQuery Form Plugin. But we need to overide the default behavior
/// of the JsonResult class in order to achieve the desired
///
public class FileUploadJsonResult : JsonResult
{
public override void ExecuteResult(ControllerContext context)
{
this.ContentType = "text/html";
context.HttpContext.Response.Write("<textarea>");
base.ExecuteResult(context);
context.HttpContext.Response.Write("</textarea>");
}
}
Và code cho Page aspx của tôi như sau:
Code cho Controller :
Sau khi có đầy đủ các phần trên, và nhiệm vụ của tôi còn lại là run demo xem thế nào?
Rất tuyệt, quá trình trình phát triển và kết quả tôi có, trong hình trên sau khi bạn run, bạn chọn một file để upload xem ra sao?
Kết quả cuối cùng tôi có. tuyệt vời phải không các bạn. Trong các cách lám upload file, tôi rất thích cách phát triển này. nhanh, gọn và nhẹ.
Bài viết của DangTrung



.jpg)
