开发者

How is better save and load a picture on c# (asp.net) and SQL Server?

开发者 https://www.devze.com 2023-03-18 23:04 出处:网络
I want to save pictures, and show them in a gridview with the name, description, price, and other things, but I don\'t know how to do it. First, how should I upload the image? I\'m currently using a W

I want to save pictures, and show them in a gridview with the name, description, price, and other things, but I don't know how to do it. First, how should I upload the image? I'm currently using a Windows Forms application to save the other information, but I now need to save the image as well. These images will need to be viewed from a web page in an ASP.NET application.

I don't think I need to save the path, because other users will be loading it via the web page on their computer. What's the best format to use in the database varbinary or image. I'm not sure how to use these or how to make them visible in the gridview. I do know how to do it if I have the path to the image, but not if the image is in the database开发者_如何学C.

Can anyone show me how to store the image in a database then display it in a gridview?


If you want to store it in the database, you should use varbinary. It's functionally equivalent to the image column type, but image has been deprecated in favor of varbinary(MAX). Typically, to use the image from the database you'd create an HttpHandler (or a controller/action if using ASP.NET MVC) that handles a url encoding the identifier associated with the image, for example, http://www.example.com/imagehandler.ashx?id=42. The handler, in this case, would know to find the image with id 42 in the database and construct a response from the byte array corresponding to the columns contents with the correct MIME type.

Sample code: completely untested

public class ImageHandler: IHttpHandler
{
    public void ProcessRequest (HttpContext context)
    {
         int imageID = -1;
         if (context.Request.QueryString["id"] == null || !int.TryParse( context.Request.QueryString["id"], out imageID) ) 
         {
             throw new ArgumentException("Invalid or missing image id.");
         }

         using (var context = new ImagesDataContext())
         {
              var image = context.Images.SingleOrDefault( i => i.ID == imageID );
              if (image != null)
              {
                   context.Response.ContentType = image.MimeType;
                   context.Response.BinaryWrite( image.Content );
              }
              else
              {
                  // decide how you want to handle an image that isn't found
              }
         }

    }

    public bool IsReusable
    {
        get { return false; }
    } 
}
0

精彩评论

暂无评论...
验证码 换一张
取 消