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

本文介绍了一种利用JavaScript模拟form表单的方法来实现文件下载,通过创建隐藏表单并提交查询参数,实现MVC模式下的文件下载操作。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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");
        }


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值