文件未在webmethod中下载

时间:2012-03-05 06:00:15

标签: c# asp.net

我正在使用webmethod下载.zip文件,但文件未下载。我的代码运行良好,没有错误,代码如下:  

 [WebMethod]
    public static void DownloadExtension(string ExtensionPath)
    {
        string filepath = HttpContext.Current.Server.MapPath(ExtensionPath);
        FileInfo file = new FileInfo(filepath);
        if (file.Exists)
        {
            HttpContext.Current.Response.ClearContent();
            HttpContext.Current.Response.AddHeader("Content-Disposition", "attachment; filename=" + file.Name);
            HttpContext.Current.Response.AddHeader("Content-Length", file.Length.ToString());
            HttpContext.Current.Response.ContentType = ReturnExtension(file.Extension.ToLower());
            HttpContext.Current.Response.TransmitFile(file.FullName);
            HttpContext.Current.Response.End();
        }
    }

    private static string ReturnExtension(string fileExtension)
    {
        switch (fileExtension)
        {            
            case ".zip":
                return "application/zip";  
            default:
                return "application/octet-stream";
        }
    }


我正在使用 VS2008 任何解决方案谢谢。

2 个答案:

答案 0 :(得分:1)

你可以尝试这种方法..对我来说工作正常...希望它可以帮助你...

         protected void Page_Load(object sender, EventArgs e)
{
    StartZip(Server.MapPath("directory name"), "filename");      
}

protected void StartZip(string strPath, string strFileName)
{
    MemoryStream ms = null;
    Response.ContentType = "application/octet-stream";
    strFileName = HttpUtility.UrlEncode(strFileName).Replace('+', ' ');
    Response.AddHeader("Content-Disposition", "attachment; filename=" + strFileName + ".zip");
    ms = new MemoryStream();
    zos = new ZipOutputStream(ms);
    strBaseDir = strPath + "\\";
    addZipEntry(strBaseDir);
    zos.Finish();
    zos.Close();
    Response.Clear();
    Response.BinaryWrite(ms.ToArray());
    Response.End();
}

protected void addZipEntry(string PathStr)
{
    DirectoryInfo di = new DirectoryInfo(PathStr);
    foreach (DirectoryInfo item in di.GetDirectories())
    {
        addZipEntry(item.FullName);
    }
    foreach (FileInfo item in di.GetFiles())
    {
        FileStream fs = File.OpenRead(item.FullName);
        byte[] buffer = new byte[fs.Length];
        fs.Read(buffer, 0, buffer.Length);
        string strEntryName = item.FullName.Replace(strBaseDir, "");
        ZipEntry entry = new ZipEntry(strEntryName);
        zos.PutNextEntry(entry);
        zos.Write(buffer, 0, buffer.Length);
        fs.Close();
    }
}

答案 1 :(得分:1)

尝试通过.ashx处理程序文件下载文件。