首页 > 解决方案 > C# ASP.NET MVC - 将 XML 下载到浏览器

问题描述

我正在使用 ASP.NET 4.6 MVC。我将 xml 文件作为字节数组保存在我的 SQL 数据库中。我想允许我的用户从浏览器下载文件。我没有收到任何错误,也没有下载文件。我知道那里有很多这样的问题,但我还没有看到没有下载文件的问题(甚至没有被损坏的文件)。

public ActionResult DownloadScript(int id) {
    try {
        var script = _db.PortalScripts.FirstOrDefault(i = >i.Id == id);
        if (script != null) {
            return File(script.ScriptBytes, "text/xml", script.Name);
        }
    }
    catch(Exception e) {
        FlashMessage.Danger("Error downloading script");
    }

    return RedirectToAction("Scripts");
}
    [HttpPost]
    public ActionResult UploadScript(HttpPostedFileBase file) {
        try {
            if (file.ContentLength > 0) {
                var newScript = new PortalScript {
                    Name = Path.GetFileName(file.FileName),
                    Version = "190.161",
                    Description = "This is a placeholder",
                    Displayed = true
                };

                using(MemoryStream ms = new MemoryStream()) {
                    file.InputStream.CopyTo(ms);
                    newScript.ScriptBytes = ms.ToArray();
                }

                var existingScripts = _db.PortalScripts.FirstOrDefault(s = >s.ScriptBytes == newScript.ScriptBytes);

                if (existingScripts == null) {
                    _db.PortalScripts.AddOrUpdate(newScript);
                    _db.SaveChanges();
                    FlashMessage.Confirmation(newScript.Name + " successfully uploaded");
                }
                else FlashMessage.Warning(newScript.Name + " already exists. Duplicate upload ignored.");

            }
        }
        catch(Exception ex) {
            FlashMessage.Danger("Upload failed: " + ex.Message);
        }

        return RedirectToAction("Scripts");
    }

在我的下载方法中,我的脚本变量返回了一个正确填写的模型。也不去抓。只是在没有文件的情况下被重定向回我的原始视图。有什么建议么??

标签: c#asp.net-mvc

解决方案


推荐阅读