我正在尝试下载图片
客户端HTML代码:
$.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
签名
public HttpResponseMessage DownloadFile(long id)
返回代码:
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;
更新
我尝试使用此代码返回jpeg使其成功,但从不显示图像。
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);
})
更新2:
已更改为此代码,现在可以使用
public IHttpActionResult DownloadFile(long id)
{
//code
myBytes = File.ReadAllBytes(path);
return Ok(myBytes);
}
答案 0 :(得分:1)
在将Accept标头更改为“application / octet”并将数据类型留空之前,我遇到了同样的问题。返回的jquery对象的状态为200并返回数据,但始终执行错误选项。之前我已经看过jquery数据类型或者Accept标头与Web API控制器返回的内容不匹配。错误响应中的jqXHR对象实际上显示已触发某些错误,但我还没有找到导致该行为的jquery选项或Web API响应。
<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控制器
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 request returns 200 OK, but an error event is fired instead of success