0

I am trying to download an image

Client HTML code:

$.ajax({
            url: 'http://localhost:17308/api/DownloadFile/10272',
            type: 'GET',
            dataType: 'json',
            success: function (data, textStatus, xhr) {
                console.log(data);
            },
            error: function (xhr, textStatus, errorThrown) {
                console.log('Error in Database');
            }
        }); 

This code above call the Web API just fine, but I get hit with the error --> console.log('Error in Database'); (per my console.log on error:

Web Api

Signature

public HttpResponseMessage DownloadFile(long id)

returning code:

result = new HttpResponseMessage(HttpStatusCode.OK);
var stream = new FileStream(path, FileMode.Open);
result.Content = new StreamContent(stream);
result.Content.Headers.ContentType = new MediaTypeHeaderValue(mime);
return result;
  1. Do I need to change my dataType from json to something else ( i assume so)
  2. What other ways to troubleshoot this?

UPDATE

I was trying this code for returning a jpeg it makes it to success, but never displays the image.

HTML:

<button type="button" id="Download" class="btn btn-primary">Download</button>    
<img id="test" alt="test" src="" />

Javascript:

var request = function () {
            var ajaxOptions = {};
            ajaxOptions.cache = false;
            ajaxOptions.url = "/api/DownloadFile/10272";
            ajaxOptions.type = "GET";
            ajaxOptions.headers = {};
            ajaxOptions.headers.Accept = "application/octet-stream"
            ajaxOptions.success = function (result) {
                console.log("start");
                $("#test").attr("src", "data:image/jpg;base64," + result);
                console.log("end");
            };
            ajaxOptions.error = function (jqXHR) {
                console.log("found error");
                console.log(jqXHR);
            };
            $.ajax(ajaxOptions);
        }

        $(function () {
            $('#Download').on('click', request);

        })

UPDATE 2:

Changed to this code and it now works

public IHttpActionResult DownloadFile(long id)
{
    //code
     myBytes = File.ReadAllBytes(path);
     return Ok(myBytes);
}
  • May be you should look into the "Database"? Are you able to debug and see what happens when you read the image from path via FileStream? Also What is value of mime? – vendettamit Aug 26 '15 at 02:43
  • Well I'm pretty sure it is not a database issue, mime is the byte size like 56874 which converts to KB of around the first 3 numbers (divide by 1024 i believe) . It is either 1. how the web api is handling the file and returning it... OR 2. the way in which the return is coming to the ajax call –  Aug 26 '15 at 16:15
  • mime should represent a valid media type supported by the server. e.g. new MediaTypeHeaderValue("image/png"); for images of png format. I'm not sure about what you said `"mime is the byte size like 56874"` is correct. – vendettamit Aug 26 '15 at 17:00

1 Answers1

0

I had the same problem until I changed the Accept header to "application/octet" and left the datatype blank. The jquery object being returned had a status of 200 and returned the data but always executed the error option. I have seen this before with the jquery datatype or Accept header did not match up with what was being returned by the Web API controller. The jqXHR object in the error response actually shows that some error was triggered but I have as of yet not found what jquery option or Web API response is causing the behavior.

<button id="submit" class="btn btn-primary">submit</button> 
<img id="test" alt="test" src="" />

JavaScript

var request = function () {
var ajaxOptions = {};
ajaxOptions.cache = false;
ajaxOptions.url = "/api/question3api";
ajaxOptions.type = "GET";
ajaxOptions.headers = {};
ajaxOptions.headers.Accept = "application/octet-stream"
ajaxOptions.success = function (result) {
    console.log(result);
    $("#test").attr("src", "data:image/png;base64," + result);
};
ajaxOptions.error = function (jqXHR) {
    console.log("found error");
    console.log(jqXHR);
};
$.ajax(ajaxOptions);
}

$(function () {
 $('#submit').on('click', request);

})

Api Controller

public class question3apiController : ApiController
{
    public  IHttpActionResult GetFile()
    {
        string FilePath = HttpContext.Current.Server.MapPath("~/images/images.png");
        byte [] myBytes = File.ReadAllBytes(FilePath);
        return Ok(myBytes);
    }
}

edited: Actually after reading the following the result makes sense. If the dataType of the request is set to expect JSON but some other format is returned the error event occurs.

Ajax request returns 200 OK, but an error event is fired instead of success

Community
  • 1
  • 1
Bill
  • 1,241
  • 17
  • 25
  • I am still trying to use HttpResponseMessage ( public HttpResponseMessage DownloadFile(long id) ) I was reading about the differences from IHttpActionResult vs. HttpResponseMessage , I'm about to attempt to switch as I make it to the success now, but no image displays. –  Aug 26 '15 at 16:52
  • Trying to get your stuff to work. I do return multiple file types but for testing, if ONLY trying the jpeg –  Aug 26 '15 at 17:05
  • Sweet, ok so this now works with public IHttpActionResult DownloadFile(long id) and myBytes = File.ReadAllBytes(path); return Ok(myBytes); –  Aug 26 '15 at 17:43