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;
- Do I need to change my dataType from json to something else ( i assume so)
- 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);
}