MVC 4和Jquery如何以字节为单位获取下载文件

时间:2014-08-01 14:06:22

标签: jquery asp.net-mvc asp.net-mvc-4

我目前有一个调用Action方法的Jquery ajax帖子。 action方法将文件作为字节流返回。如何下载返回给用户?那么它开始下载?返回的文件可以是从txt文件到pdf到图像文件的任何内容

 viewAttachmentDetails: function (e) {
        debugger;

        var attachmentId = $(e.target).data("id");
        var model = {};
        model = { attachmentId: attachmentId };
        var jsonData = JSON.stringify(model);
        AISApp.Ajax.postJSON(AISApp.Page.getAttachmentURL, jsonData, AISApp.Page.loaderContainer, AISApp.Page.viewAttachmentDetailsComplete);

    },

    viewAttachmentDetailsComplete: function(data)
    {
        debugger;
        window.open(data);  //<<--- what should I do here??

    },

我的Action方法如下,

public ActionResult GetAttachment(int attachmentId)
        {


            var attachmentDetails = _coesAttachments.GetAttachmentsDetails(new SearchAttachmentsCriteria
            {
                Id = attachmentId
            }).SingleOrDefault();

            if (attachmentDetails != null)
            {

                byte[] fileBytes = Encoding.ASCII.GetBytes(WebConfigurationManager.AppSettings["Attachments"].ToString() + @"\" + attachmentDetails.FileName);

                return File(fileBytes, System.Net.Mime.MediaTypeNames.Application.Octet, attachmentDetails.OriginalFileName);

            }


            return new EmptyResult();


        }

1 个答案:

答案 0 :(得分:0)

试试这个

更新您的Action方法以返回FileResult

示例:

public FileResult Download()
{

            byte[] byteArray = Encoding.ASCII.GetBytes(xml);//replace xml with actual data
            return File(byteArray, System.Net.Mime.MediaTypeNames.Application, "filename");
}