如何让点击超链接显示图片变成下载链接?

 

 

 

 

 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace httpHandler
{
    /// <summary>
    /// xiazai1 的摘要说明
    /// </summary>
    public class xiazai1 : IHttpHandler
    {

        public void ProcessRequest(HttpContext context)
        {
            context.Response.ContentType = "image/jpeg";
            //context.Response.AddHeader("content-disposition","attachment:filename=haha.jpg");
            //或者使用下面的asp.net方式添加报文头,AddHeader是一个老的asp兼容的方法
            context.Response.AppendHeader("content-disposition", "attachment:filename=haha.jpg");
            context.Response.WriteFile("content/DSC06942.JPG");
        }

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

vs2010在项目里面新建一个一般处理程序就可以得到上面的结果,如果没有其中的AppendHeader,会直接在浏览器上没有提示的显示出这张图片.不过有点郁闷的是调整发现这个文件名老是不对,显示的是xiazai1.jpg,准确的应该是haha.jpg,和老师做的一样,结果却不同,和Web服务器有关系?还是浏览器?

查了一下资料,原来是打错了一个字符,在attachment后面应该跟上分号,而不是冒号!

如果想将haha.jpg改成中文的,需要对中文做一下编码处理,比如

public void ProcessRequest(HttpContext context)
        {
            context.Response.ContentType = "image/JPEG";
            //context.Response.AddHeader("content-disposition","attachment:filename=haha.jpg");
            //或者使用下面的asp.net方式添加报文头,AddHeader是一个老的asp兼容的方法

            string filename = HttpUtility.UrlEncode("哈哈.jpg");
            context.Response.AddHeader("Content-Disposition", "attachment;filename="+filename);
            context.Response.WriteFile("content/DSC06942.JPG");
        }


 
posted @ 2013-01-17 21:39  tony_ontheway  阅读(8879)  评论(1编辑  收藏  举报