[英]Web Api return Image as HttpResponseMessage but .ajax call is not getting the download
我正在嘗試下載圖片
客戶端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);
}
在將Accept標頭更改為“ application / octet”並將數據類型留為空白之前,我遇到了同樣的問題。 返回的jquery對象的狀態為200,並返回了數據,但始終執行error選項。 我以前用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設置為期望JSON,但返回了其他格式,則會發生錯誤事件。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.