C# 如果在asp.net 3.5中找不到项目,如何从“图像”文件夹传递默认图像
我有一个ASHX处理程序,可以在服务器端发出请求后显示图像 以下是我的处理程序代码:C# 如果在asp.net 3.5中找不到项目,如何从“图像”文件夹传递默认图像,c#,asp.net,C#,Asp.net,我有一个ASHX处理程序,可以在服务器端发出请求后显示图像 以下是我的处理程序代码: <%@ WebHandler Language="C#" Class="DisplayImage" %> using System; using System.Web; using System.Linq; public class DisplayImage : IHttpHandler { public void ProcessRequest(HttpContext context)
<%@ WebHandler Language="C#" Class="DisplayImage" %>
using System;
using System.Web;
using System.Linq;
public class DisplayImage : IHttpHandler {
public void ProcessRequest(HttpContext context)
{
int userId;
if (context.Request.QueryString["userId"] != null)
userId = Convert.ToInt32(context.Request.QueryString["userId"]);
else
throw new ArgumentException("No parameter specified");
var query = Helper.GetPhotos().Where(p => p.user_id.Equals(userId)).Select(p => p).ToList();
byte[] imageData = null;
foreach (var item in query)
{
if (item != null)
{
imageData = item.Image.ToArray();
context.Response.ContentType = "image/jpeg";
context.Response.BinaryWrite(imageData);
}
else
{
//get images from images named folder and parse it to byte array
}
}
}
public bool IsReusable {
get {
return false;
}
}
}
使用制度;
使用System.Web;
使用System.Linq;
公共类DisplayImage:IHttpHandler{
公共void ProcessRequest(HttpContext上下文)
{
int用户标识;
if(context.Request.QueryString[“userId”]!=null)
userId=Convert.ToInt32(context.Request.QueryString[“userId”]);
其他的
抛出新ArgumentException(“未指定参数”);
var query=Helper.GetPhotos().Where(p=>p.user_id.Equals(userId)).Select(p=>p.ToList();
字节[]imageData=null;
foreach(查询中的var项)
{
如果(项!=null)
{
imageData=item.Image.ToArray();
context.Response.ContentType=“image/jpeg”;
context.Response.BinaryWrite(imageData);
}
其他的
{
//从名为文件夹的图像中获取图像,并将其解析为字节数组
}
}
}
公共布尔可重用{
得到{
返回false;
}
}
}
这里是if(item!=null)
的else部分,我只想从服务器端的images文件夹传递默认图像
请帮帮我…你可以这样做:
if (item != null)
{
imageData = item.Image.ToArray();
context.Response.ContentType = "image/jpeg";
context.Response.BinaryWrite(imageData);
}
else
{
//get images from images named folder and parse it to byte array
imageData =System.IO.File.ReadAllBytes(System.Web.HttpContext.Current.Server.MapPath("~/Images/DefaultImage.jpg"));
context.Response.ContentType = "image/jpeg";
context.Response.BinaryWrite(imageData);
}
您可以使用完整路径从文件中获取字节
public static byte[] GetByteFromFile(string FullPath)
{
byte[] ImageData = null;
if (System.IO.File.Exists(FullPath))
{
System.IO.FileStream fs = new System.IO.FileStream(FullPath, System.IO.FileMode.Open, System.IO.FileAccess.Read);
ImageData = new byte[fs.Length];
fs.Read(ImageData, 0, System.Convert.ToInt32(fs.Length));
fs.Close();
}
return ImageData;
}
我认为if(System.IO.FIle.Exsists())语句应该告诉您映像是否存在,在else中,您可以获取默认映像…我在服务器端的images文件夹中有修复映像。在这里,我只是在server.mappath with convert.toByte或其他最佳选项的帮助下,将此映像传递给字节数组。我为文件添加了IO命名空间,但ReadAllBytes未获得ReadAllBytes方法是否需要另一个命名空间。您可以使用完全限定的命名空间来执行System.IO.File.ReadAllBytes。它将在字节数组