[求助] 用ashx從northwind讀取圖片不成功的,哪裡錯了

來源:互聯網
上載者:User

代碼參考自http://blog.joycode.com/liuhuimiao/archive/2005/06/03/52554.aspx?Pending=true

 1<%@ WebHandler Language="C#" Class="Handler" %>
 2
 3using System;
 4using System.IO;
 5using System.Web;
 6
 7public class Handler : IHttpHandler {
 8
 9    public bool IsReusable {
10        get {
11            return true;
12        }
13    }
14    
15    public void ProcessRequest (HttpContext context) {
16        // Set up the response settings
17        context.Response.ContentType = "image/jpeg";
18        context.Response.Cache.SetCacheability(HttpCacheability.Public);
19        context.Response.BufferOutput = false;
20        
21        
22        // Setup the PhotoID Parameter
23        Int32 id = -1;
24        Stream stream = null;
25        if (context.Request.QueryString["PhotoID"] != null && context.Request.QueryString["PhotoID"] != "") {
26            id = Convert.ToInt32(context.Request.QueryString["PhotoID"]);
27            stream = (GetPhoto(id));
28        } else {
29            return ;
30        }
31      // Write image stream to the response stream
32        const int buffersize = 1024 * 16;
33        byte[] buffer = new byte[buffersize];
34        int count = stream.Read(buffer, 0, buffersize);
35        while (count > 0) {
36            context.Response.OutputStream.Write(buffer, 0, count);
37            count = stream.Read(buffer, 0, buffersize);
38        }
39    }
40    public Stream GetPhoto(int photoId)
41    {
42        SqlConnection myConnection = new SqlConnection(ConfigurationManager.ConnectionStrings["Personal"].ConnectionString);
43        SqlCommand myCommand = new SqlCommand("SELECT [Photo] FROM [Employees] WHERE [EmployeeID]=@EmployeeID",myConnection);
44        myCommand.CommandType = CommandType.Text;
45        myCommand.Parameters.Add(new SqlParameter("@EmployeeID", photoId));
46        myConnection.Open();
47        object result = myCommand.ExecuteScalar();
48
49        try
50        {
51            return new MemoryStream((byte[])result);
52        }
53        catch (ArgumentNullException e)
54        {
55            return null;
56        }
57        finally
58        {
59            myConnection.Close();
60        }
61    }
62
63}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.