Web Api return Image as HttpResponseMessage but .ajax call is not getting the download
我正在尝试下载图像
客户端HTML代码:
1 2 3 4 5 6 7 8 9 10 11 | $.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'); } }); |
上面的代码调用Web API就好了,但是我遇到了错误 - > console.log('数据库错误'); (根据我的console.log错误:
Web Api
签名
1 | public HttpResponseMessage DownloadFile(long id) |
返回代码:
1 2 3 4 5 |
UPDATE
I was trying this code for returning a jpeg it makes it to success, but never displays the image.
HTML:
1 2 | <button type="button" id="Download" class="btn btn-primary">Download</button> <img id="test" alt="test" src="" /> |
使用Javascript:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 | 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); }) |
更新2:
已更改为此代码,现在可以使用了
1 2 3 4 5 6 | public IHttpActionResult DownloadFile(long id) { //code myBytes = File.ReadAllBytes(path); return Ok(myBytes); } |
我有同样的问题,直到我将Accept标头更改为"application / octet"并将数据类型留空。 返回的jquery对象的状态为200并返回数据,但始终执行错误选项。 之前我已经看过jquery数据类型或者Accept标头与Web API控制器返回的内容不匹配。 错误响应中的jqXHR对象实际上显示已触发某些错误,但我还没有找到导致该行为的jquery选项或Web API响应。
1 2 | <button id="submit" class="btn btn-primary">submit</button> <img id="test" alt="test" src="" /> |
JavaScript的
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 | 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控制器
1 2 3 4 5 6 7 8 9 | public class question3apiController : ApiController { public IHttpActionResult GetFile() { string FilePath = HttpContext.Current.Server.MapPath("~/images/images.png"); byte [] myBytes = File.ReadAllBytes(FilePath); return Ok(myBytes); } } |
编辑:实际上,在阅读以下内容后,结果是有道理的。 如果请求的dataType设置为expect JSON但返回了其他格式,则会发生错误事件。
Ajax请求返回200 OK,但是触发了错误事件而不是成功