2017-08-01 52 views
0

我從數據庫中獲取的ByteArray:通過API的文件返回字節組與C#

byte[] bytDocu; 

我想通過一個API返回此ByteArray爲文件:

[HttpGet] 
[Route("GetFile/{key}")] 
public IHttpActionResult GetFile(int key) 
{ 

    try 
    { 
     byte[] bytDocu = _documentService.getFile(key); 
     return Ok(result); 
    } 
    catch (Exception e) 
    { 
     return BadRequest(e.Message); 
    } 
} 

我怎麼打開Bytearray進入文件? 我該如何將它交給Ok()函數?

感謝您的幫助:)

回答

3

使用下面的代碼

localFilePath = "file path"; 
HttpResponseMessage response = new HttpResponseMessage(HttpStatusCode.OK); 
response.Content = new StreamContent(new FileStream(filepath, FileMode.Open, FileAccess.Read)); 
response.Content.Headers.ContentDisposition = new System.Net.Http.Headers.ContentDispositionHeaderValue("attachment"); 
response.Content.Headers.ContentDisposition.FileName = fileName; 
response.Content.Headers.ContentType = new MediaTypeHeaderValue("application/pdf or set your content type"); 

return response; 
+0

它爲我工作。 –