简体   繁体   中英

Create a downloadable file in C# (Umbraco)

For a recent project, We're trying to create a downloadable file in C# Umbraco, but I can't seem to get it to work. For the download I'm using System.Web.HttpContext.Current.Response. The function is called after a button is pressed in Umbraco CMS. The function is called, but doesn't respond with a download. The function is implemented in a class that inherits from System.Web.Http.ApiController.

I'm aware that this question matches some other questions, but I've tried different solutions and I feel like I'm overlooking something.

Source code:

[Route("feedback")]
[HttpPost]
public void Add(FeedbackRequest feedback)
{
    var Response = HttpContext.Current.Response;

    string filePath = "C:\\testfile.txt";
    var file = new FileInfo(filePath);

    if (file.Exists)
    {
        Response.Clear();
        Response.ClearHeaders();
        Response.ClearContent();
        Response.AddHeader("Content-Disposition", "attachment; filename=" + file.Name);
        Response.AddHeader("Content-Length", file.Length.ToString());

        //Doesn't work with plain/text either
        Response.ContentType = "application/force-download";
        Response.Flush();
        Response.TransmitFile(file.FullName);
        try
        {
            Response.End();
        }
        catch (ThreadAbortException err)
        {

        }
        catch (Exception err)
        {
        }
    }

}

You have your method set as void, it should be returning a result

public ActionResult Add(FeedbackRequest feedback)
{   
    string filepath = "some filepath";
    byte[] filedata = File.ReadAllBytes(filepath);
    string contentType = MimeMapping.GetMimeMapping(filepath);

    var contentInfo = new System.Net.Mime.ContentDisposition
    {
        FileName = "download filename",
        Inline = false,//ask browser for download prompt
    };

    Response.AppendHeader("Content-Disposition", contentInfo.ToString());

    return File(filedata, contentType);
}

The problem was my js. I had:

            $http.get('/someurl/Export').             
             success(function (data) { 
                //console.log(data); 
                $scope.importOutput = data; 
        });

The fix was:

window.open('/someurl/Export', '_blank'); 

Thanks for all the answers. I assumed the js was fine, because it was handling the call, but it appears it was not.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM