0

I have web api controller method to download excel file, by passing "FileName" as a parameter, can anybody help me how to download the file using $.Ajax or any other possible way.

API Controller method

[HttpPost]
[Route("api/POSTargets/DownloadFile")]
public HttpResponseMessage DownloadExcel(string FileName)
    {
        var filePath = @"~/POSTarget/" + FileName;

        var path = HttpContext.Current.Server.MapPath(filePath);
        if (path != null)
            return FileAsAttachment(path, "Errors POS Target.xlsx");
        return new HttpResponseMessage(HttpStatusCode.NotFound);
    }


    public static HttpResponseMessage FileAsAttachment(string path, string filename)
    {
        HttpResponseMessage result = new HttpResponseMessage(HttpStatusCode.OK);
        var stream = new FileStream(path, FileMode.Open);
        result.Content = new StreamContent(stream);
        result.Content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
        result.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment");
        result.Content.Headers.ContentDisposition.FileName = filename;
        return result;
    }

---View

 function downloadFile() {
        debugger;
        var fileName= "Error POS Target372016182355.xlsx";
        $.ajax({
            url: "http://localhost/RPMS/api/POSTargets/DownloadFile",
            type: "POST",
            data: fileName
        }).done(function (data) {
            alert(data);
        }).error(function (data) {
           alert(data);
        });


    }
Rocky Royalson
  • 119
  • 2
  • 6
  • are you asking how to pass parameter to jquery method with file name? – profesor79 Mar 08 '16 at 11:27
  • Change type: "GET" into type: "POST" – SilentTremor Mar 08 '16 at 12:30
  • Hello Profesor and Tremor, thanks for your reply. I need your help. I want to pass file name to post it to web api controller method, and want to download a file, I tried to change Type to "POSt" however it didn't work, I stuck with this issue since 7hrs, please help me. Thanks in advance!!! – Rocky Royalson Mar 08 '16 at 16:54

0 Answers0