Ajay
Ajay

Reputation: 653

MVC Web Api 2: How to allow parallel download of files

Well, below is my code which relates out to downloading of a zip file. All things work fine, but it is not able to download up the file when there is one ongoing download request.

public class ZipController : ApiController
    {
        [System.Web.Http.AcceptVerbs("GET", "POST")]
        [System.Web.Http.HttpGet]
        public HttpResponseMessage DownloadFile()
        {
            var zipPath = ConfigurationManager.AppSettings["FilePath"];
            var result = new HttpResponseMessage(HttpStatusCode.OK);
            try
            {
                if (File.Exists(zipPath))
                {
                    var stream = new FileStream(zipPath, FileMode.Open);
                    result.Content = new StreamContent(stream);
                    result.Content.Headers.ContentType =
                        new MediaTypeHeaderValue("application/octet-stream");
                    result.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment")
                    {
                        FileName = "abc.zip"
                    };
                }
            }
            catch (Exception ex)
            {
                LogError.LogErrorToFile(ex);
            }
            return result;
        }

    }

Upvotes: 0

Views: 513

Answers (1)

Ajay
Ajay

Reputation: 653

It worked when I provided up the file access rights.

public class ZipController : ApiController
    {
        [System.Web.Http.AcceptVerbs("GET", "POST")]
        [System.Web.Http.HttpGet]
        public HttpResponseMessage DownloadFile()
        {
            var zipPath = ConfigurationManager.AppSettings["FilePath"];
            var result = new HttpResponseMessage(HttpStatusCode.OK);
            var stream = new FileStream(zipPath, FileMode.Open, FileAccess.ReadWrite, FileShare.ReadWrite);
            try
            {
                if (File.Exists(zipPath))
                {

                    result.Content = new StreamContent(stream);
                    result.Content.Headers.ContentType =
                        new MediaTypeHeaderValue("application/octet-stream");
                    result.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment")
                    {
                        FileName = "abc.zip"

                    };

                }
            }
            catch (Exception ex)
            {
                LogError.LogErrorToFile(ex);
            }
            return result;
        }
     }

Upvotes: 1

Related Questions