【问题标题】:Downloading File in ASP mvc .net在 ASP mvc .net 中下载文件
【发布时间】:2012-01-03 14:04:49
【问题描述】:

我将下载链接放在 jqgrid 中,我的文件存储在服务器上而不是数据库中,文件类型不同(扩展名) 我希望用户在点击下载链接时下载文件

加载jqgrid的代码如下

public object GetJSONFormatProjectDetails(List<ProjectMasterDTO> listProjectDTO, int SkipCount)
    {
        var data = (listProjectDTO.Select(c => new
        {
            id = c.ProjectID,
            cell = new[]
                        {
                            c.ProjectName,
                            c.OfficeName,
                            c.ProjectType,
                            c.ProjectNature,
                            c.EntrepreneurName,
                            c.Year + " Years " +c.Month  + " Months " + c.Day + " Days" ,
                            c.ConcessionWEFdate,
                            c.ProjectStartDate,
                            c.ProjectEndDate,
                            c.isRoadApplicable,
                            (c.FilePath != "NA" ) ? "<a href='#' style='color:green' onclick='DownLoadFile(\""+URLEncrypt.EncryptParameters(new string[]{ "filepath =" +c.FilePath.Replace("/","$").Replace(" ","#").Trim()})+"\");return false;'>"+(c.FilePath != "NA" ? "DownLoad":"Not Available") + " </a>" : "<span style='color:Red' >Not Available</span>"

                        }
        })).ToArray().Skip(SkipCount);
        return data;
    }

JS文件代码如下

function DownLoadFile(param) {
$.ajax({
url: "/Home/GetFile?parameter=" + param,
    cache: false,
    type: "POST",
    async: false
});

}

Controller中的代码如下

  public ActionResult GetFile(string parameter)
    {
        string queryStringParameters = Request.QueryString["parameter"];

        if (queryStringParameters == null)
        {
            throw new Exception("Url is tampered");
        }

        string[] parameterArray = queryStringParameters.Split('/');

        string param = null;
        string hash = null;
        string key = null;
        if (parameterArray.Length == 3)
        {
            param = parameterArray[0];
            hash = parameterArray[1];
            key = parameterArray[2];
        }
        if (!(string.IsNullOrEmpty(parameter)))
        {
            Dictionary<string, string> parameters = URLEncrypt.DecryptParameters(new string[] { param, hash, key });
            string FilePath =string.Empty ;
            parameters.TryGetValue("filepath", out FilePath);
            FilePath = FilePath.Replace('$','\\');

            // DownloadFile(FilePath);

            string name = Path.GetFileName(FilePath);
            string ext = Path.GetExtension(FilePath);
            string type = "";
            // set known types based on file extension  
            if (ext != null)
            {
                switch (ext.ToLower())
                {

                    case ".pdf":
                        type = "Application/pdf";
                        break;

                    case ".doc":

                    case ".docx":
                        type = "Application/msword";
                        break;

                    case ".jpg":

                    case ".bmp":

                    case ".tiff":

                    case ".png":

                    case ".gif":

                    case ".jpeg":
                        type = "Application/Image";
                        break;
                    default:
                        type = "Application";
                        break;

                }
            }
            Response.AppendHeader("content-disposition", "attachment; filename=" + name);

            if (type != "")
            {
                Response.ContentType = type;
            }
            String FullFilePath = @"F:\MHTOLL\ContractUploadDetails\" + name;
            //return File(new FileStream(path + fileName, FileMode.Open), "text/plain", fileName);
          //  return File(new FileStream(FullFilePath, FileMode.Open), type, name);
            return File(FullFilePath, type,name);

        }
        return null;
    }

现在不要介意返回 null 和异常处理

还建议在下载文件时显示 .gif 动画。

【问题讨论】:

    标签: asp.net-mvc jqgrid download


    【解决方案1】:

    我认为您不能使用 AJAX 调用来下载文件。

    我认为这个答案会让你得到你想要的。请务必阅读有关下载提示和 MIME 类型的 cmets。 Download File Using Javascript/jQuery

    【讨论】:

      【解决方案2】:

      我最近遇到了同样的问题,并意识到 AJAX 无法下载文件。尝试使用 ActionLink:

      @Html.ActionLink("ButtonName", "controllerFunctionName", "controllerName", new { functionParamName = paramValue })

      你会在控制器中包含你的函数:

      public ActionResult controllerFunctionName(type functionParamName){ // do your download here }

      【讨论】:

      • 简单地说,AJAX 不适用于 Response.function 调用。但是,我没有理由,如果有人可以为我解释这一点,我将不胜感激。
      • 这是我最初发布问题的地方:stackoverflow.com/questions/15458477/…。我使用的是 AJAX,但没有将其视为问题。我认为这个错误是在控制器功能中。
      猜你喜欢
      • 2017-02-07
      • 1970-01-01
      • 1970-01-01
      • 2013-06-03
      • 2014-07-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-08-02
      相关资源
      最近更新 更多