2014-02-10 2 views
0

웹 API 컨트롤러가 있는데 파일 다운로드를 시뮬레이트하는 함수를 작성하려고합니다. 실제 파일이 아니며 즉석에서 생성 된 것입니다.WEB API로 파일 다운로드 시뮬레이션

내가하고 싶은 것은 파일 크기가있는 매개 변수를 api에 보내고 즉시 생성 된 "바이너리"파일을 반환해야합니다. 이 PHP 코드와 유사한

뭔가 : 내가 찾은

<?php 
    $filesize = 20971520; // 20 Mo 

    if (isset($_POST['d'])) { 
     header('Cache-Control: no-cache'); 
     header('Content-Transfer-Encoding: binary'); 
     header('Content-Length: '. $filesize); 

     for($i = 0 ; $i < $filesize ; $i++) { 
      echo chr(255); 
     } 
    } 
?> 

가장 가까운 솔루션은 다음과 같은 것이었다 :

HttpResponseMessage response = new HttpResponseMessage(); 
response.Content = new StreamContent(new FileStream(@"path to image")); // this file stream will be closed by lower layers of web api for you once the response is completed. 
response.Content.Headers.ContentType = new MediaTypeHeaderValue("image/png"); 

나는 그것으로 주위를 연주 및 변경 시도했지만 운이 없었다.

누군가가 올바른 방향으로 나를 가리키며 나를 도울 수 있다면 칭찬 할 것입니다.

감사합니다.

답변

1

이런 종류의 제품입니까?

public class FakeDownloadController: ApiController 
{ 
    public HttpResponseMessage Get([FromUri] int size) 
      { 
       var result = new HttpResponseMessage(HttpStatusCode.OK); 
       byte[] data = new byte[size]; 
       var stream = new MemoryStream(data); 
       result.Content = new StreamContent(stream); 
       result.Content.Headers.ContentType = new MediaTypeHeaderValue("application/binary"); 
       var contentDisposition = new ContentDispositionHeaderValue("attachment"); 
       contentDisposition.FileName = string.Format("{0}.{1}", "dummy","bin"); 
       result.Content.Headers.ContentDisposition = contentDisposition; 
       return result; 
      } 
} 

사용 :

http://localhost:port/api/FakeDownload/?size=6543354 

"dummy.bin"라는 NULL 가득 ~ 6메가바이트 파일을 반환합니다.

희망이 있습니다.