2017-10-19 1 views
1

내 WebApi에 문제가 있습니다. 요청에 따라 응답은 json 또는 csv 중 하나로 반환됩니다. 직렬화에 대해서는 NewtonSoft.Json을 사용하고 내 자신의 CsvMediaTypeFormatter을 사용합니다. 우체부에서 테스트하는 한 응답은 예상대로 작동합니다.WebApi 파일로 응답 다운로드

응답이 csv 인 경우 브라우저가 파일을 저장하도록 강제하고 싶습니다. 나는 우체부를 사용하여 내 API를 테스트 할 때

public override void SetDefaultContentHeaders(Type type, HttpContentHeaders headers, MediaTypeHeaderValue mediaType) 
{ 
    base.SetDefaultContentHeaders(type, headers, mediaType); 

    headers.ContentDisposition = new ContentDispositionHeaderValue("attachment") 
           { 
            FileName = "content.csv" 
           }; 
} 

, 나는 또한 헤더 content-disposition: attachment; filename=content.csv을 보여, 몸으로 CSV 내용을 참조하십시오 다음과 같이 그것을 달성하기 위해, 내 CsvMediaTypeFormatter에서 나는 SetDefaultContentHeaders 방법을 무효화한다.

하지만 Firefox (Chrome, Edge)를 사용해 보았을 때 "파일 저장 ..."대화 상자가 표시되지 않습니다. 그러나 dev 도구는 호출이 이루어 졌음을 나타내며 content-disposition 헤더 값을 갖는 응답을 표시합니다. text/csv, text/plain, application/octet-stream 또는 application/x-unknown,하지만 성공 :

나는 다양한 Content-type 값을 시도했다.

내가 잘못하고있는 아이디어가 있습니까?

답변

1

http 호출을하기 위해 일부 js 프레임 워크를 사용하는 경우 수동으로 내용을 파일로 덤프해야 할 수도 있습니다. 다음은 AngularJS 및 Angular2의 예입니다.

AngularJS와 :

this.$http(req).success(data => { 
    const file = new Blob([data], 
     { 
      type: "text/csv" 
     }); 

    const a = document.createElement("a"); 
    a.href = URL.createObjectURL(file); 
    a.target = "_blank"; 
    a.download = `yourfilename.csv`; 
    document.body.appendChild(a); 
    a.click(); 
}); 

Angular2 +

downloadFile(data: Response){ 
    const file = new Blob([data], 
     { 
      type: "text/csv" 
     }); 
    var url= window.URL.createObjectURL(blob); 
    window.open(url); 
} 

How to create and save file to local fileSystem using AngularJS?

How do I download a file with Angular2

+1

아, 멍청한 놈 내가 무엇을 ... – Szeki

관련 문제