2015-01-05 6 views
1

특정 폴더의 파일 목록을 하이퍼 링크로 표시하고 싶습니다. 사용자가 링크를 클릭하면 해당 파일이 열리 며 다운로드하거나 볼 수 있지만ASHX 핸들러 값이 null이 될 수 없음

{"Value cannot be null.\r\nParameter name: filename"} 나는 많은 방법을 시도했습니다 라인 context.Response.WriteFile(context.Request.QueryString["files"]);

에서하지만 아무 소용이 : 일정한 오류 속담이있다.

ASHX 파일 :

protected void Page_Load(object sender, EventArgs e) 
{ 
    if (!Page.IsPostBack) 
    { 
     var directory = new DirectoryInfo("C:\\temp\\Safety&Security"); 
     var files = (from f in directory.GetFiles() 
        orderby f.LastWriteTime descending 
        select f).First(); 
     //string[] files = Directory.GetFiles(@"C:\temp\Safety&Security"); 
     //files = files.Substring(files.LastIndexOf(("\\")) + 1); 
     rpt.DataSource = files; 
     rpt.DataBind(); 
    } 

    if (!Page.IsPostBack) 
    { 
     string[] files = Directory.GetFiles(@"C:\temp\marketing"); 
     Repeater1.DataSource = files; 
     Repeater1.DataBind(); 
    } 

    if (!Page.IsPostBack) 
    { 
     string[] files = Directory.GetFiles(@"C:\temp\IT"); 
     Repeater2.DataSource = files; 
     Repeater2.DataBind(); 
    } 
} 

protected void rpt_ItemDataBound(object sender, RepeaterItemEventArgs e) 
{ 
    if (e.Item.ItemType == ListItemType.AlternatingItem || e.Item.ItemType == ListItemType.Item) 
    { 
     string file = e.Item.DataItem as string; 
     HyperLink hyp = e.Item.FindControl("hyp") as HyperLink; 
     hyp.Text = file; 
     hyp.NavigateUrl = string.Format("~/Handlers/FileHandler.ashx?file={0}", file); 
     FileInfo f = new FileInfo(file); 
     FileStream s = f.Open(FileMode.OpenOrCreate, FileAccess.Read); 
    } 
} 

public void ProcessRequest(HttpContext context) 
{ 
    //Track your id 
    //string id = context.Request.QueryString["id"]; 
    context.Response.Clear(); 
    context.Response.Buffer = true; 
    context.Response.ContentType = "application/octet-stream"; 
    context.Response.AddHeader("Content-Disposition", "attachment; filename=" + context.Request.QueryString["files"]); 
    context.Response.WriteFile(context.Request.QueryString["files"]); 
    context.Response.End(); 
} 

public bool IsReusable 
{ 
    get { return false; } 
} 

이 인덱스 페이지 코드입니다 : 당신은 바보 같은 실수를 한

<li class='has-sub'><a href='#'><span>Safety, QA & Security</span></a> 
    <ul> 
     <asp:Repeater ID="rpt" runat="server" OnItemDataBound="rpt_ItemDataBound"> 
      <ItemTemplate> 
       <asp:HyperLink ID="hyp" runat="server" target="_blank" a href="/Handlers/FileHandler.ashx?id=7"/> 
       <%-- another method of listing all files in specific folder --%>    
       <%--<% foreach(var file in Directory.GetFiles("C:\\temp\\Safety&Security", "*.*", SearchOption.AllDirectories)) { %> 
       <li><%= file.Substring(file.LastIndexOf(("\\"))+1) %></li>  
       <% } %> --%> 
      </ItemTemplate> 
     </asp:Repeater> 
    </ul> 
</li> 
+1

하나의 if 문에서 3 개의 다른 문 대신에'If (! Page.IsPostback) {....} '를 모두 그룹화하여 정리할 수 있습니다 – Prescott

답변

2

!

hyp.NavigateUrl = string.Format("~/Handlers/FileHandler.ashx?file={0}", file); 

context.Response.WriteFile(context.Request.QueryString["files"]); 

당신은 '파일'로 쿼리 문자열을 설정하지만, 존재하지 않는 '파일'과 같은 쿼리 문자열을 읽고.

context.Response.WriteFile(context.Request.QueryString["file"]); 

편집을 시도해보십시오

이 코드를 사용해보십시오. 먼저 c : \ temp에 test.txt라는 파일을 추가하고 텍스트를 입력하십시오. 핸들러에서

<li class='has-sub'><a href='/Handlers/FileHandler.ashx?file=c:\temp\test.txt'><span>Safety, QA & Security</span></a></li> 

: 귀하의 영문에서

public void ProcessRequest(HttpContext context) 
{ 
    //Track your id 
    //string id = context.Request.QueryString["id"]; 
    context.Response.Clear(); 
    context.Response.Buffer = true; 
    context.Response.ContentType = "application/octet-stream"; 
    context.Response.AddHeader("Content-Disposition", "attachment; filename=" + context.Request.QueryString["file"]); 
    context.Response.WriteFile(context.Request.QueryString["file"]); 
    context.Response.End(); 
} 

public bool IsReusable 
{ 
    get { return false; } 
} 

는 핸들러에 중단 점을 설정하고 디버깅 할 때 핸들러가 당한다 있는지 확인하십시오. 이 코드는 데이터 바인딩에 대한 주석에서 언급 한 다른 문제로 인해 작동하지 않지만 적어도 핸들러에서 쿼리 문자열을 가져와 텍스트 파일을 다운로드해야합니다.

+0

안녕하세요, 이미 변경했으나 동일한 오류가 여전히 존재합니다. –

+0

파일 위로 마우스를 가져 가면 파일 링크가 어떻게 생깁니 까? 오류를 던지는 줄에 중단 점을 설정하면 context.Request에 무엇이 있습니까? – garethb

+0

파일 중 하나의 하이퍼 링크를 가리키면 "/Handlers/FileHandler.ashx?id=7"이 ​​표시됩니다 –

관련 문제