如何从控制器中的文件夹下载PDF

时间:2018-04-20 10:27:25

标签: c# asp.net-web-api

[Route("pdfdownload")]
[HttpGet]
public IHttpActionResult Getpdfdownload(string parameter)
{
   HttpResponse Response = HttpContext.Current.Response;

   string PdfFileName = parameter;

   string path = ConfigurationManager.AppSettings["SISource"].ToString() + "\\" + PdfFileName; 

   var dataBytes = File.ReadAllBytes(path);

   var dataStream = new MemoryStream(dataBytes);

   return new GetPDFDownload(dataStream, Request, PdfFileName);

}


public class GetPDFDownload : IHttpActionResult
{
     MemoryStream bookStuff;
 string PdfFileName;

 HttpRequestMessage httpRequestMessage;

 HttpResponseMessage httpResponseMessage;



public GetPDFDownload(MemoryStream data, HttpRequestMessage request, string filename)
{
   bookStuff = data;

   httpRequestMessage = request;

   PdfFileName = filename;
}

public System.Threading.Tasks.Task<HttpResponseMessage> 

ExecuteAsync(System.Threading.CancellationToken cancellationToken)
{

    httpResponseMessage = httpRequestMessage.CreateResponse(HttpStatusCode.OK);

    httpResponseMessage.Content = new StreamContent(bookStuff);

    httpResponseMessage.Content.Headers.ContentDisposition = new 

    System.Net.Http.Headers.ContentDispositionHeaderValue("attachment");

    httpResponseMessage.Content.Headers.ContentDisposition.FileName = PdfFileName;

    httpResponseMessage.Content.Headers.ContentType = new 

    System.Net.Http.Headers.MediaTypeHeaderValue("application/pdf");


    return System.Threading.Tasks.Task.FromResult(httpResponseMessage);

  }
}

1 个答案:

答案 0 :(得分:0)

要下载任何文件,您可以使用以下代码段。它简短而且非常简单。您可以自定义一点并使用它。

    //Route: http://localhost:56928/api/values/parameter=asdasd
    [HttpGet]
    public IActionResult Get(string parameter)
    {
        var path = @"D:\Work\"+parameter;
        var fileName = System.IO.Path.GetFileName(path);
        FileContentResult result = new FileContentResult(System.IO.File.ReadAllBytes(path), "application/octet-stream")
        {
            FileDownloadName = fileName
        };
        return result;
    }

或者你可以这样做:

    public HttpResponseMessage Get()
    {
        var path = @"D:\Work\Tryouts\split.txt";
        HttpResponseMessage result = new HttpResponseMessage(HttpStatusCode.OK);
        var stream = new FileStream(path, FileMode.Open, FileAccess.Read);
        result.Content = new StreamContent(stream);
        result.Content.Headers.ContentType =
            new MediaTypeHeaderValue("application/octet-stream");
        return result;
    }