SORU
6 HAZİRAN 2014, Cuma


ASP.NET Web API bir yöntem angularjs kullanarak dosya indirme

Benim angularjs project, tıklandığında bir dosya döndüren WebAPİ bir yöntem için bir get isteği yaptığında bir bağlantı etiketi ettim. Şimdi, dosya isteği başarılı olduktan sonra kullanıcı indirilmesini istiyorum. Nasıl yapabilirim?

Bağlantı etiketi :

<a href="#" ng-click="getthefile()">Download img</a>

Angularjs :

$scope.getthefile = function () {        
        $http({
            method: 'GET',
            cache: false,
            url: $scope.appPath   'CourseRegConfirm/getfile',            
            headers: {
                'Content-Type': 'application/json; charset=utf-8'
            }
        }).success(function (data, status) {
            console.log(data) // displays text data if the file is a text file, binary if it's an image            
// now what should I write here to download the file I receive from the WebAPI method.
        }).error(function (data, status) {

        });
    }

WebAPİ benim yöntem :

[Authorize]
[Route("getfile")]
public HttpResponseMessage GetTestFile()
{
    HttpResponseMessage result = null;
    var localFilePath = HttpContext.Current.Server.MapPath("~/timetable.jpg");

    if (!File.Exists(localFilePath))
    {
        result = Request.CreateResponse(HttpStatusCode.Gone);
    }
    else
    {// serve the file to the client
        result = Request.CreateResponse(HttpStatusCode.OK);
        result.Content = new StreamContent(new FileStream(localFilePath, FileMode.Open, FileAccess.Read));
        result.Content.Headers.ContentDisposition = new System.Net.Http.Headers.ContentDispositionHeaderValue("attachment");
        result.Content.Headers.ContentDisposition.FileName = "SampleImg";                
    }

    return result;
}

CEVAP
9 HAZİRAN 2014, PAZARTESİ


Ajax kullanarak ikili dosya indirme desteği büyük değil, pek çok şey under development as working drafts.

Basit indirme yöntemi:

Tarayıcı İstenen dosya sadece indirme aşağıdaki kodu kullanarak olabilir, ve bu tüm tarayıcılarda desteklenir, ve belli ki WebApi isteği aynı tetikleyecektir.

$scope.downloadFile = function(downloadPath) { 
    window.open(downloadPath, '_blank', '');  
}

Ajax ikili indirme yöntemi:

Ajax ikili dosya indirmek için kullanan bazı tarayıcılarda yapılabilir ve aşağıda Chrome, Internet Explorer, FireFox ve Safari son çeşit olarak çalışacak bir uygulama.

Kullanır arraybuffer yanıt yazın, daha sonra dönüştürülmüş içine bir JavaScript blob, daha sonra da sunulan Kaydet kullanarak saveBlob yöntem - ama bu sadece şu anda, Internet Explorer veya devre içine bir blob veri URL hangisi tarafından açılan tarayıcı, tetikleme yükleme iletişim halinde mıme türü desteklenmiyor görüntüleme tarayıcısı.

Internet Explorer 11 Desteği (Sabit)

Not: Internet Explorer 11 gibi kullanarak msSaveBlob fonksiyon yarasaydı edilmiş, yumuşatılmış - belki de bir güvenlik özelliği, ama daha çok bir kusur, Yani kullanarak var saveBlob = navigator.msSaveBlob || navigator.webkitSaveBlob ... etc. belirlemek için kullanılabilir saveBlob destek neden bir istisna; dolayısıyla neden kodu aşağıda şimdi testleri için navigator.msSaveBlob ayrı ayrı. Teşekkürler? Microsoft

// Based on an implementation here: web.student.tuwien.ac.at/~e0427417/jsdownload.html
$scope.downloadFile = function(httpPath) {
    // Use an arraybuffer
    $http.get(httpPath, { responseType: 'arraybuffer' })
    .success( function(data, status, headers) {

        var octetStreamMime = 'application/octet-stream';
        var success = false;

        // Get the headers
        headers = headers();

        // Get the filename from the x-filename header or default to "download.bin"
        var filename = headers['x-filename'] || 'download.bin';

        // Determine the content type from the header or default to "application/octet-stream"
        var contentType = headers['content-type'] || octetStreamMime;

        try
        {
            // Try using msSaveBlob if supported
            console.log("Trying saveBlob method ...");
            var blob = new Blob([data], { type: contentType });
            if(navigator.msSaveBlob)
                navigator.msSaveBlob(blob, filename);
            else {
                // Try using other saveBlob implementations, if available
                var saveBlob = navigator.webkitSaveBlob || navigator.mozSaveBlob || navigator.saveBlob;
                if(saveBlob === undefined) throw "Not supported";
                saveBlob(blob, filename);
            }
            console.log("saveBlob succeeded");
            success = true;
        } catch(ex)
        {
            console.log("saveBlob method failed with the following exception:");
            console.log(ex);
        }

        if(!success)
        {
            // Get the blob url creator
            var urlCreator = window.URL || window.webkitURL || window.mozURL || window.msURL;
            if(urlCreator)
            {
                // Try to use a download link
                var link = document.createElement('a');
                if('download' in link)
                {
                    // Try to simulate a click
                    try
                    {
                        // Prepare a blob URL
                        console.log("Trying download link method with simulated click ...");
                        var blob = new Blob([data], { type: contentType });
                        var url = urlCreator.createObjectURL(blob);
                        link.setAttribute('href', url);

                        // Set the download attribute (Supported in Chrome 14  / Firefox 20 )
                        link.setAttribute("download", filename);

                        // Simulate clicking the download link
                        var event = document.createEvent('MouseEvents');
                        event.initMouseEvent('click', true, true, window, 1, 0, 0, 0, 0, false, false, false, false, 0, null);
                        link.dispatchEvent(event);
                        console.log("Download link method with simulated click succeeded");
                        success = true;

                    } catch(ex) {
                        console.log("Download link method with simulated click failed with the following exception:");
                        console.log(ex);
                    }
                }

                if(!success)
                {
                    // Fallback to window.location method
                    try
                    {
                        // Prepare a blob URL
                        // Use application/octet-stream when using window.location to force download
                        console.log("Trying download link method with window.location ...");
                        var blob = new Blob([data], { type: octetStreamMime });
                        var url = urlCreator.createObjectURL(blob);
                        window.location = url;
                        console.log("Download link method with window.location succeeded");
                        success = true;
                    } catch(ex) {
                        console.log("Download link method with window.location failed with the following exception:");
                        console.log(ex);
                    }
                }

            }
        }

        if(!success)
        {
            // Fallback to window.open method
            console.log("No methods worked for saving the arraybuffer, using last resort window.open");
            window.open(httpPath, '_blank', '');
        }
    })
    .error(function(data, status) {
        console.log("Request failed with status: "   status);

        // Optionally write the error out to scope
        $scope.errorDetails = "Request failed with status: "   status;
    });
};

Kullanımı:

var downloadPath = "/files/instructions.pdf";
$scope.downloadFile(downloadPath);

Notlar:

Aşağıdaki başlıklar dönmek için WebApi yönteminizi değiştirmeniz gerekir:

  • Dosya göndermek için x-filename Başlığı kullandım. Bu ancak content-disposition Başlığı düzenli ifadeler kullanarak dosya ayıklamak olabilir kolaylık sağlamak için özel bir başlık.

  • Tarayıcı veri biçimini bilir yanıtınız için content-type mıme Başlığı çok belirlemelisiniz.

Bu yardımcı olur umarım.

Bunu Paylaş:
  • Google+
  • E-Posta
Etiketler:

YORUMLAR

SPONSOR VİDEO

Rastgele Yazarlar

  • LiveForGodsKingdom

    LiveForGodsK

    6 NİSAN 2008
  • Matt Steffanina

    Matt Steffan

    1 EYLÜL 2011
  • thelonelyisland

    thelonelyisl

    23 Aralık 2005