Angular를 사용하여 파일을 다운로드하는 방법JS와 MVC API 호출?
저는 AngularJS를 사용하고 있으며, 첨부 파일과 함께 HttpResponseMessage를 반환하는 MVC 4 API를 가지고 있습니다.
var result = new MemoryStream(pdfStream, 0, pdfStream.Length) {
Position = 0
};
var response = new HttpResponseMessage {
StatusCode = HttpStatusCode.OK,
Content = new StreamContent(result)
};
response.Content.Headers.ContentDisposition =
new ContentDispositionHeaderValue("attachment") {
FileName = "MyPdf.pdf"
};
response.Content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
return response;
fileDownload...라는 jQuery 플러그인을 사용하고 있습니다.파일을 아름답게 다운로드 할 수 있습니다.'각선'으로 할 수 있는 방법을 못 찾았어요어떤 도움이라도 감사합니다.
// _e
저도 같은 문제가 있었어요.파일세이버라는 Javascript 라이브러리를 사용하여 해결했습니다.
그냥 전화하세요.
saveAs(file, 'filename');
전체 http 게시 요청:
$http.post('apiUrl', myObject, { responseType: 'arraybuffer' })
.success(function(data) {
var file = new Blob([data], { type: 'application/pdf' });
saveAs(file, 'filename.pdf');
});
여기에서는 angularjs http 요청을 클라이언트가 수행해야 하는 API에 대해 설명합니다.WS URL과 파라미터(있는 경우)를 케이스에 맞게 조정하기만 하면 됩니다.나오에의 대답과 이 답변이 뒤섞여 있다.
$http({
url: '/path/to/your/API',
method: 'POST',
params: {},
headers: {
'Content-type': 'application/pdf',
},
responseType: 'arraybuffer'
}).success(function (data, status, headers, config) {
// TODO when WS success
var file = new Blob([data], {
type: 'application/csv'
});
//trick to download store a file having its URL
var fileURL = URL.createObjectURL(file);
var a = document.createElement('a');
a.href = fileURL;
a.target = '_blank';
a.download = 'yourfilename.pdf';
document.body.appendChild(a); //create the link "a"
a.click(); //click the link "a"
document.body.removeChild(a); //remove the link "a"
}).error(function (data, status, headers, config) {
//TODO when WS error
});
코드 설명:
- Angularjs는 다음 URL에서 file.pdf를 요구합니다.
/path/to/your/API
. - 응답에 성공했습니다.
- 프런트 엔드에서 JavaScript를 사용하여 다음과 같은 트릭을 실행합니다.
- html 링크 ta를 만듭니다.
<a>
. - 하이퍼링크를 클릭합니다.
<a>
태그, JS 사용click()
기능.
- html 링크 ta를 만듭니다.
- html 삭제
<a>
태그, 클릭 후.
다양한 투고에 따라...XHR을 통해 다운로드를 트리거할 수 없습니다.다운로드 조건을 실장할 필요가 있었습니다.그 때문에, 저의 솔루션은 다음과 같습니다.
//make the call to the api with the ID to validate
someResource.get( { id: someId }, function(data) {
//confirm that the ID is validated
if (data.isIdConfirmed) {
//get the token from the validation and issue another call
//to trigger the download
window.open('someapi/print/:someId?token='+ data.token);
}
});
어떻게든, 혹은 언젠가 XHR을 사용하여 다운로드가 트리거되어 두 번째 콜을 회피할 수 있으면 좋겠습니다.//_e
angularjs로 하는 방법은 두 가지가 있습니다.
1) 서비스 콜로 직접 리다이렉트하여
<a href="some/path/to/the/file">clickme</a>
2) 숨김 양식을 제출합니다.
$scope.saveAsPDF = function() {
var form = document.createElement("form");
form.setAttribute("action", "some/path/to/the/file");
form.setAttribute("method", "get");
form.setAttribute("target", "_blank");
var hiddenEle1 = document.createElement("input");
hiddenEle1.setAttribute("type", "hidden");
hiddenEle1.setAttribute("name", "some");
hiddenEle1.setAttribute("value", value);
form.append(hiddenEle1 );
form.submit();
}
어떤 요소를 게시해야 할 때 숨겨진 요소를 사용합니다.
<button ng-click="saveAsPDF()">Save As PDF</button>
엄청난 사람들의 해결책이 나에게 잘 먹혔다.그러나 Internet Explorer 10+에도 파일이 저장되지 않았습니다.IE 브라우저에서는 아래 코드가 작동했습니다.
var file = new Blob(([data]), { type: 'application/pdf' });
if (window.navigator.msSaveOrOpenBlob) {
navigator.msSaveBlob(file, 'fileName.pdf');
}
또 다른 예로는Blob()
코드:
function save(url, params, fileName){
$http.get(url, {params: params}).success(function(exporter) {
var blob = new Blob([exporter], {type: "text/plain;charset=utf-8;"});
saveAs(blob, fileName);
}).error(function(err) {
console.log('err', err);
});
};
// Save as Code
function saveAs(blob, fileName){
var url = window.URL.createObjectURL(blob);
var doc = document.createElement("a");
doc.href = url;
doc.download = fileName;
doc.click();
window.URL.revokeObjectURL(url);
}
이렇게 해서 이 문제를 해결했다.
$scope.downloadPDF = function () {
var link = document.createElement("a");
link.setAttribute("href", "path_to_pdf_file/pdf_filename.pdf");
link.setAttribute("download", "download_name.pdf");
document.body.appendChild(link); // Required for FF
link.click(); // This will download the data file named "download_name.pdf"
}
string trackPathTemp = track.trackPath;
//The File Path
var videoFilePath = HttpContext.Current.Server.MapPath("~/" + trackPathTemp);
var stream = new FileStream(videoFilePath, FileMode.Open, FileAccess.Read);
var result = new HttpResponseMessage(HttpStatusCode.OK)
{
Content = new StreamContent(stream)
};
result.Content.Headers.ContentType = new MediaTypeHeaderValue("video/mp4");
result.Content.Headers.ContentRange = new ContentRangeHeaderValue(0, stream.Length);
// result.Content.Headers.Add("filename", "Video.mp4");
result.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment")
{
FileName = "Video.mp4"
};
return result;
FileSaver.js를 사용하여 문제를 해결했습니다.도움말 감사합니다.아래 코드는 도움이 되었습니다.
'$'
DownloadClaimForm: function (claim)
{
url = baseAddress + "DownLoadFile";
return $http.post(baseAddress + "DownLoadFile", claim, {responseType: 'arraybuffer' })
.success(function (data) {
var file = new Blob([data], { type: 'application/pdf' });
saveAs(file, 'Claims.pdf');
});
}
angular service write angular file server.js 및 Blob.js를 사용하는 angular service가 있습니다.
vm.download = function(text) {
var data = new Blob([text], { type: 'text/plain;charset=utf-8' });
FileSaver.saveAs(data, 'text.txt');
};
언급URL : https://stackoverflow.com/questions/14215049/how-to-download-file-using-angularjs-and-calling-mvc-api
'programing' 카테고리의 다른 글
각도 $위치패스가 기능하지 않음 (0) | 2023.03.17 |
---|---|
문자열 변수 덤프로의 JSON (0) | 2023.03.17 |
MongoDB Java 드라이버 MongoOptions를 실가동용으로 설정하는 방법 (0) | 2023.03.12 |
RxJ의 파이프란 무엇입니까? (0) | 2023.03.12 |
React.컴포넌트 대 리액트순수 컴포넌트 (0) | 2023.03.12 |