C# 从FileResult处理程序在ajax中显示图像(操作)
我正在为当前项目使用Asp.net Core Razor页面。。。我有一个页面处理程序(操作),用于使用Ajax将图像发送到我的页面。。。我用ajax将请求发送给我的处理程序,我的响应适合图像到页面,但图像不会显示在我的img src标记中C# 从FileResult处理程序在ajax中显示图像(操作),c#,jquery,css,asp.net-web-api,asp.net-core,C#,Jquery,Css,Asp.net Web Api,Asp.net Core,我正在为当前项目使用Asp.net Core Razor页面。。。我有一个页面处理程序(操作),用于使用Ajax将图像发送到我的页面。。。我用ajax将请求发送给我的处理程序,我的响应适合图像到页面,但图像不会显示在我的img src标记中 public IActionResult OnGetDeleteImage(ImageType imageType) { return File(DefaultImage(imageType), "image/png", Guid.NewGuid()
public IActionResult OnGetDeleteImage(ImageType imageType)
{
return File(DefaultImage(imageType), "image/png", Guid.NewGuid().ToString());
}
。。。DefaultImage获取服务器上的映像路径。
和ajax请求:
$.ajax({
type: 'GET',
url: deleteImagePath,
beforeSend: function (xhr) {
xhr.setRequestHeader("XSRF-TOKEN",
$('input:hidden[name="__RequestVerificationToken"]').val());
},
success: function (data) {
alert(data);
$("#" + id).attr("src",data);
},
error: function (err) {
alert(err);
}
我的代码返回图像内容,但在imgsrc中不显示。
谢谢。您试图将图像的二进制内容放入
src
属性,该属性需要url,而不是实际数据。您可以尝试将该图像格式化为数据url,它应该可以工作
在本例中,我假设您的DefaultImage
方法返回PNG文件的路径,但我不能确定这一点。要返回数据uri,它将如下所示:
public IActionResult OnGetDeleteImage(ImageType imageType)
{
return new ContentResult() {
Content = "data:image/png;base64," + System.Convert.ToBase64String(System.IO.File.ReadAllBytes(DefaultImage(imageType))),
ContentType = "text/plain"
});
}
public IActionResult OnGetDeleteImage(ImageType imageType)
{
return new ContentResult() {
Content=GetPublicPathTo(DefaultImage(imageType)), //this should return something like "/img/the_image_to_display.png"
ContentType="text/plain"
}
}
在IE浏览器中,数据uri只能在32K以下的图像上工作,上面的代码效率不高
如果可能(例如,图像存储在服务器端应用程序的一部分,可以作为静态文件提供),最好使用C#方法向图像文件返回一个可公开访问的uri,然后在更新src
时,浏览器将从该uri下载该文件。看起来是这样的:
public IActionResult OnGetDeleteImage(ImageType imageType)
{
return new ContentResult() {
Content = "data:image/png;base64," + System.Convert.ToBase64String(System.IO.File.ReadAllBytes(DefaultImage(imageType))),
ContentType = "text/plain"
});
}
public IActionResult OnGetDeleteImage(ImageType imageType)
{
return new ContentResult() {
Content=GetPublicPathTo(DefaultImage(imageType)), //this should return something like "/img/the_image_to_display.png"
ContentType="text/plain"
}
}