网页API返回形象的Htt presponseMessage但阿贾克斯呼叫未得到下载 [英] Web Api return Image as HttpResponseMessage but .ajax call is not getting the download

查看:133
本文介绍了网页API返回形象的Htt presponseMessage但阿贾克斯呼叫未得到下载的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想下载一个图像

客户端HTML code:

  $。阿贾克斯({
            网址:HTTP://本地主机:17308 / API / DownloadFile / 10272,
            键入:GET,
            数据类型:JSON,
            成功:功能(数据,textStatus,XHR){
                的console.log(数据);
            },
            错误:函数(XHR,textStatus,errorThrown){
                的console.log(在数据库错误');
            }
        });
 

这code以上调用Web API就好了,但我会碰到一个错误 - >的console.log('错误在数据库'); (按我的console.log上的错误:

网络阿比

签名

 公开的Htt presponseMessage DownloadFile(长ID)
 

返回code:

 的结果=新的Htt presponseMessage(的HTTPStatus code.OK);
VAR流=新的FileStream(路径,FileMode.Open);
result.Content =新StreamContent(流);
result.Content.Headers.ContentType =新MediaTypeHeaderValue(MIME);
返回结果;
 

  1. 请我需要改变的JSON我的数据类型设置为别的东西(我认为如此)
  2. 还有什么其他的方法来解决此?

更新

  

我想这code返回一个JPEG这使得它的成功,但永远显示图像。

HTML:

 <按钮式=按钮ID =下载级=BTN BTN小学>下载< /按钮>
< IMG ID =测试ALT =测试SRC =/>
 

JavaScript的:

  VAR请求=功能(){
            变种ajaxOptions = {};
            ajaxOptions.cache = FALSE;
            ajaxOptions.url =/ API / DownloadFile / 10272;
            ajaxOptions.type =GET;
            ajaxOptions.headers = {};
            ajaxOptions.headers.Accept =应用程序/八位字节流
            ajaxOptions.success =功能(结果){
                的console.log(开始);
                $(#考)ATTR。(SRC,数据:图像/ JPG; BASE64,+结果);
                的console.log(结束);
            };
            ajaxOptions.error =功能(jqXHR){
                的console.log(发现错误);
                执行console.log(jqXHR);
            };
            $阿贾克斯(ajaxOptions);
        }

        $(函数(){
            $('#下载')上(咔哒,要求)。

        })
 

更新2:

更改为此code和它现在的作品

 公共IHttpActionResult DownloadFile(长ID)
{
    // code
     myBytes = File.ReadAllBytes(路径);
     返回OK(myBytes);
}
 

解决方案

我有同样的问题,直到我改变了Accept报头为应用程序/八位位组,离开了数据类型的空白。返回jQuery对象有200个状态和返回的数据,但始终执行的错误选项。我已经看到了这之前,jQuery的数据类型或接受头没有什么正在由Web API控制器返回匹配。在错误响应的jqXHR对象实际表明,一些错误被触发,但我目前还没有发现什么jQuery的选项或Web API响应导致出现该问题。

 <按钮ID =提交级=BTN BTN小学>提交< /按钮>
< IMG ID =测试ALT =测试SRC =/>
 

JavaScript的

  VAR请求=功能(){
变种ajaxOptions = {};
ajaxOptions.cache = FALSE;
ajaxOptions.url =/ API / question3api;
ajaxOptions.type =GET;
ajaxOptions.headers = {};
ajaxOptions.headers.Accept =应用程序/八位字节流
ajaxOptions.success =功能(结果){
    执行console.log(结果);
    $(#考)ATTR。(SRC,数据:图像/ PNG; BASE64,+结果);
};
ajaxOptions.error =功能(jqXHR){
    的console.log(发现错误);
    执行console.log(jqXHR);
};
$阿贾克斯(ajaxOptions);
}

$(函数(){
 $('#提交')上(咔哒,要求)。

})
 

API控制器

 公共类question3apiController:ApiController
{
    公共IHttpActionResult的GetFile()
    {
        字符串的文件路径= HttpContext.Current.Server.MapPath(〜/图片/ images.png);
        byte []的myBytes = File.ReadAllBytes(文件路径);
        返回OK(myBytes);
    }
}
 

编辑:阅读下面的结果是有道理的后其实。如果请求的数据类型设置为预期JSON,但一些其他的格式返回错误事件发生。

<一个href="http://stackoverflow.com/questions/6186770/ajax-request-return-200-ok-but-error-event-is-fired-instead-of-success">AJAX请求返回200 OK,但错误事件被触发,而不是成功

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);
}

解决方案

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 return 200 OK but error event is fired instead of success

这篇关于网页API返回形象的Htt presponseMessage但阿贾克斯呼叫未得到下载的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆