首页 > 解决方案 > 从链接下载文件已发送到电子邮件

问题描述

我正在尝试发送一封包含文件下载链接的电子邮件,但是单击该文件没有任何反应,我无法从该链接下载该文件。

在我点击下载文件的链接后,它在浏览器中打开了空白选项卡,但文件尚未下载

public ActionResult DownLoadTraining(ContactUsModel model)
    {
        SendEmail sendemail = new SendEmail();

        string toEmail = ConfigurationManager.AppSettings["ContactUsEmail"];

        var keys = new Dictionary<string, string>() {
            { "Firstname", model.Firstname },
            { "Lastname", model.Lastname },
            { "Email", model.Email },
            { "Orgnization", model.Orgnization },
            { "Message", model.Message }
        };
//here i build the link to donwload it .
        string DownLoadlink = "<a download  href='http://www.yoursite.com/folders/yourfile.txt' target='_blank'>Click me to DownLoad</a>";


        if (keys != null && keys.Count != 0)
        {
            string body = string.Join(Environment.NewLine, keys.Select(x => $"{x.Key}: {x.Value}"));

            sendemail.Send(new EmailModel()
            {
                Body = DownLoadlink,
                Subject = "DownLoad Training Message",
                To = new List<string>() { model.Email },

            });

            return Json(new { val = true }, JsonRequestBehavior.AllowGet);
        }
        else
        {
            return Json(new { val = false }, JsonRequestBehavior.AllowGet);
        }
    }

任何建议。

标签: c#asp.net-mvchtml

解决方案


当用户单击电子邮件中的 URL 时,创建一种下载文件的方法。生成链接为

http://yourdomain.com/Controller/Action?FilePath=/Folder/FileName.txt

public FileResult Download(string FilePath)
{
    DocPath = System.Web.HttpUtility.UrlDecode(FilePath);

    var comPath = HttpContext.Server.MapPath(FilePath);
    byte[] fileBytes = System.IO.File.ReadAllBytes(comPath);
    string fileName = Path.GetFileName(comPath);
    return File(fileBytes, System.Net.Mime.MediaTypeNames.Application.Octet, fileName);
}

推荐阅读