如何从服务器文件夹下载不在项目解决方案内的文本文件

时间:2016-12-19 10:14:40

标签: c# asp.net-mvc file download

我想从Kendo网格行点击按钮下载文本文件。我有一个选定行的Id并将其传递给我 控制器,现在它没有下载文件,因为它显示下面的错误。你的错误似乎是固定的

Failed to load resource: net::ERR_RESPONSE_HEADERS_MULTIPLE_CONTENT_DISPOSITION

文件命名如下:e669a7e7-7eb2-4cfa-b950-3b79ed621a57

public ActionResult DownloadIndex(int id)
{
    try
    {
        string Filelocation = "MyServerLocationFolder";
        OnePossModel md = new Models.OnePossModel();
        JsonParamBuilder myBuilder = new JsonParamBuilder();
        myBuilder.AddParam<Guid>("userid", System.Guid.Parse(User.Identity.GetUserId()));
        myBuilder.AddParam<int>("id", Convert.ToInt32(id));

        string jsonReq = Models.JsonWrapper.JsonPOST(ApiBaseUrl +  "/WriteFile", myBuilder.GetJSonParam());
        string poassFilename = Models.DeserialiseFromJson<string>.DeserialiseApiResponse(jsonReq);

        string filepath = Filelocation + poassFilename.ToString();
        byte[] filedata = System.IO.File.ReadAllBytes(filepath);
        string contentType = MimeMapping.GetMimeMapping(filepath);

        var cd = new System.Net.Mime.ContentDisposition
        {

            FileName = poassFilename,
            Inline = true,
        };
        Response.AddHeader("Content-Disposition", "attachment;filename=\"" + poassFilename + "\"");
        return File(filedata, "application/txt", Server.UrlEncode(poassFilename)); 
    }
    catch (Exception ex)
    {
        throw ex;
    }
}

1 个答案:

答案 0 :(得分:0)

使用“text / plain”代替“application / txt”:

public ActionResult DownloadIndex(int id)
{
    try
    {
        string Filelocation = "MyServerLocationFolder";
        OnePossModel md = new Models.OnePossModel();
        JsonParamBuilder myBuilder = new JsonParamBuilder();
        myBuilder.AddParam<Guid>("userid", System.Guid.Parse(User.Identity.GetUserId()));
        myBuilder.AddParam<int>("id", Convert.ToInt32(id));

        string jsonReq = Models.JsonWrapper.JsonPOST(ApiBaseUrl +  "/WriteFile", myBuilder.GetJSonParam());
        string poassFilename = Models.DeserialiseFromJson<string>.DeserialiseApiResponse(jsonReq);

        string filepath = Filelocation + poassFilename.ToString();
        byte[] filedata = System.IO.File.ReadAllBytes(filepath);

        return File(filedata, "text/plain", Server.UrlEncode(poassFilename)); 
    }
    catch (Exception ex)
    {
        throw ex;
    }
}