.NET MVC实现文件下载的实例

来源:互联网 发布:淘宝显示地址怎么改 编辑:程序博客网 时间:2024/06/05 05:48

js的部分是我从网上搜索到的,http://www.zhuoda.org/xiezhi/102548.html


采用模拟form的方式实现下载,虽然看起来像webform的形式,但是MVC确实可行。

js:

index.js

function downLoadFile(elementID) {    var form = $("<form>");   //定义一个form表单    form.attr('style', 'display:none');   //在form表单中添加查询参数    form.attr('target', '');    form.attr('method', 'post');    form.attr('action', "/Home/DownloadFile");    var input1 = $('<input>');    input1.attr('type', 'hidden');    input1.attr('name', 'fileContent');    input1.attr('value', { fileContent: encodeURI($("#" + elementID).html()) });    $('body').append(form);  //将表单放置在web中    form.append(input1);   //将查询参数控件提交到表单上    form.submit();   //表单提交}

C#:

HomeController.cs:

public FileResult DownloadFile(string fileContent)        {            string content = Server.UrlDecode(fileContent);            string folderPath = DOWNLOADFOLDERPATH;            string fileName = string.Format("tmp_{0}.docx", Guid.NewGuid().ToString("N"));            string localFolderPath = Server.MapPath(folderPath);            string localFileName = Server.MapPath(folderPath + fileName);            if (!System.IO.Directory.Exists(localFolderPath))            {                System.IO.Directory.CreateDirectory(localFolderPath);            }            if (System.IO.File.Exists(localFileName))            {                System.IO.File.Delete(localFileName);            }            Application app = new Application();            app.Visible = false;//设置为程序不可见            Document doc = app.Documents.Add(Type.Missing, Type.Missing, Type.Missing, Type.Missing);            doc.Paragraphs.Last.Range.Text = content;            var docFormat = Microsoft.Office.Interop.Word.WdSaveFormat.wdFormatDocumentDefault;            doc.SaveAs(localFileName, docFormat);            doc.Close();            app.Quit();            return File(folderPath + fileName, "application/vnd.openxmlformats-officedocument.wordprocessingml.document", "downloadfile.docx");        }


0 0
原创粉丝点击