下载附件后,浏览器直接打开附件

本文介绍了一个文件下载控制器的具体实现过程,包括验证权限、检查文件是否存在等步骤,并详细说明了如何设置HTTP响应头来正确返回文件内容及类型。此外,还特别强调了浏览器支持的文件格式及其限制。

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

   public ActionResult Download(string dirRelativePath, string fileName)
        {
            string token = Request.QueryString["token"];
            if (htTokens != null && !string.IsNullOrEmpty(token) && htTokens.Contains(Guid.Parse(token)))
            {
                string uploadPath = System.Configuration.ConfigurationManager.AppSettings["BPMAttachments"];
                string dirAbsolutePath = uploadPath + dirRelativePath;

                if (!System.IO.File.Exists(dirAbsolutePath))
                {
                    return Content("提示:文件在磁盘上不存在");
                }
                htTokens.Remove(token);
                //HttpContext.Response.AddHeader("content-disposition", "attachment;filename=" + fileName);
                //return File(dirAbsolutePath, "application/octet-stream");
                var contentType = MimeMapping.GetMimeMapping(fileName);
                HttpContext.Response.AddHeader("content-disposition", "inline;filename=" + fileName);
                return File(dirAbsolutePath, contentType);
            }
            else
            {
                return Content("提示:没有权限");
            }
        }

 

注意:

1.return File(dirAbsolutePath, contentType); 中contentType不能是"application/octet-stream",需要获取文件mimetype后,指定contentType

2.浏览器支持打开的文件格式有限,例如:txt、html、png、gif。。。。。。

转载于:https://www.cnblogs.com/xuguanghui/p/5871906.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值