Click here to Skip to main content
14,599,199 members

Document should be downloaded in uploaded format ( word(doc, docx) or ppt(ppt, pptx), excel or jpeg or PDF or gif or png)

Member 10033441 asked:

Open original thread
Hi All,

I am trying to download file but there is no content present after download.Please assist me to resolve it.Below is my code.

WebApi Code
-------------
[Authorize]
        [HttpPost]
        [Route("downloadStaticDocument")]
        public HttpResponseMessage downloadStaticDocument(OrderItemReview order)
        {

            HttpResponseMessage httpResponseMessage = new HttpResponseMessage();
            string fileName = "";
            string fileExtension = "";
            byte[] dataStream = new byte[0];
            string downloadName = order.itemDetails.staticDocumentName;
            try
            {
                Log.Debug("starting downloadStaticDocument");
                dataStream = Convert.FromBase64String(order.itemDetails.staticDocumentBase64);
                Log.Debug("fetching file names");
                fileName = Path.GetFileNameWithoutExtension(downloadName);
                fileExtension = Path.GetExtension(downloadName);
                Log.Debug("fileName : " + fileName);
                Log.Debug("fileExtension : " + fileExtension);

                httpResponseMessage.Content = new ByteArrayContent(dataStream.ToArray());
                httpResponseMessage.Content.Headers.Add("x-filename", fileName);
                //httpResponseMessage.Content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
                httpResponseMessage.Content.Headers.ContentType = new MediaTypeHeaderValue(GetMimeType(fileExtension));
                httpResponseMessage.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment");

                string contentType = string.Empty;
                string ext = Path.GetExtension(downloadName).ToLower();
                switch (ext)
                {
                    case ".pdf":
                        contentType = "application/pdf";
                        break;
                    case ".doc":
                    case ".docx":
                        contentType = "application/msword";
                        break;
                    case ".xls":
                    case ".xlsx":
                        contentType = "application/vnd.ms-excel";
                        break;
                    case ".txt":
                        contentType = "text/plain";
                        break;
                    case ".jpg":
                        contentType = "image/JPEG";
                        break;
                    case ".png":
                        contentType = "image/PNG";
                        break;
                    case ".rtf":
                        contentType = "application/rtf";
                        break;
                    default:
                        break;
                }


                httpResponseMessage.Content.Headers.ContentType = new MediaTypeHeaderValue(contentType);

                return httpResponseMessage;
            }
            catch (Exception ex)
            {
                Log.Error(ex);

                return this.Request.CreateResponse(HttpStatusCode.InternalServerError, ex);
            }
        }


Angularjs Service calling code
--------------------
var _downloadStaticDocument = function (orderDetails) {
    
        debugger;
        var request = $http({
            method: "post",
            url: serviceBase + "api/orders/downloadStaticDocument",
            data: orderDetails,
            responseType: 'arraybuffer'
            
        });
        return request;
    }


AngularJs download function code
---------------------------------
$scope.downloadStaticDocument = function (orderDetails) {
        debugger;
        $rootScope.isLoading = true;
        $scope.ProcessFileName = orderDetails.itemDetails.productFullName + ".pdf";

        var promise = ordersManagementService.downloadStaticDocument(orderDetails);
            promise.then(function (response) {

                //for IE Compatibility to dowload blob data
                var anchor = angular.element('<a/>');
                var blob = new Blob([response.data]);
                var fileName = orderDetails.itemDetails.productName;
                if (window.navigator && window.navigator.msSaveOrOpenBlob) {
                    window.navigator.msSaveOrOpenBlob(blob);
                    $rootScope.isLoading = false;
                } else {
                    anchor.attr({
                        href: window.URL.createObjectURL(blob),
                        target: '_blank',
                        download: $scope.ProcessFileName
                    })[0].click();
                    $rootScope.isLoading = false;
                }
            
            ngToast.create({
                content: fileName + " Downloaded successfully.",
                className: 'success',
                dismissOnTimeout: true,
                timeout: 6000
            });

        }, function (error) {
            ngToast.create({
                content: error.data.message,
                className: 'error',
                dismissOnTimeout: true,
                timeout: 6000
            });
        });

    }


What I have tried:

I am not able to identify the cause.Can you please some one help me on it
Tags: WebAPI2, Angular.js

Preview



When answering a question please:
  1. Read the question carefully.
  2. Understand that English isn't everyone's first language so be lenient of bad spelling and grammar.
  3. If a question is poorly phrased then either ask for clarification, ignore it, or edit the question and fix the problem. Insults are not welcome.
  4. Don't tell someone to read the manual. Chances are they have and don't get it. Provide an answer or move on to the next question.
Let's work to help developers, not make them feel stupid.
Please note that all posts will be submitted under the The Code Project Open License (CPOL).




CodeProject, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100