Doc
Doc

Reputation: 179

How to handle download return File Result from controller ? MVC

I am not able to download file result in js. I am returning File Result to the js but dont know how to download it

To be short and specific i am returning word document from controller to js in which i need to download it and handle it in js.

My js method in which i am calling method and file result is returning to.

vm.establishmentAllRecord = function (page) {
            if (page != undefined) {
                vm.page = page;
            }
            var searchCriteria = {
                From: vm.From,
                To: vm.To,
                Region: vm.SelectedRegion
            }
surveyService.establishmentAllRecord(searchCriteria, (vm.page * vm.pagesize), vm.pagesize, vm.sortBy, vm.sortingDirection).then(function (d) {
                var result = JSON.parse(d.data.data);
                ???
            });

I need to ask how can i handle return File Result from controller on ??? this place and download

Hopes for your suggestions

EDITED:

i have return file system from controller is in this way,

 FileResult result1 = PrintSurveyDetailsReport(VisitId); 
return result1; 

result1 contains 'ContentType="application/octet-stream"' , "FileContents" and "FileDownloadName" 

Upvotes: 0

Views: 1354

Answers (1)

Wasef Anabtawi
Wasef Anabtawi

Reputation: 1021

Use the following function

 var downloadFile = function (data, fileName, contentType) {
    contentType = contentType || "application/octet-stream";
    var blobObject = new Blob([data], {type: contentType});
    try {
        window.navigator.msSaveOrOpenBlob(blobObject, fileName);
    }
    catch (exp) {
        var link = document.createElement('a');
        link.setAttribute('href', URL.createObjectURL(blobObject));
        link.setAttribute('download', fileName);
        document.body.appendChild(link); // Required for FF
        link.click();
        document.body.removeChild(link);
    }
};

Upvotes: 0

Related Questions