从目录下载文件 [英] Download file from a directory

查看:71
本文介绍了从目录下载文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我遇到了无法通过指定文件路径来下载文件的情况,但问题是该文件是以未知格式下载的.下面的代码显示了下载过程:

如果(e.CommandName =="ViewFiles")
{

int索引= Convert.ToInt32(e.CommandArgument);

GridViewRow行= gvunclassified.Rows [index];

字符串除法= row.Cells [4] .Text;

字符串文件名= row.Cells [1] .Text;

字符串路径= @"NewFolder1" +"\\" +除法+"\\" +未分类" +"\\" +文件名;
字符串驱动器= @"C:\ Website2 \ RecordsManagement";
字符串temppath = Path.Combine(驱动器,路径);


//要下载的文件路径.

字符串filepath = temppath;

//用于将文件保存到客户端系统的文件名.
字符串文件名= Path.GetFileName(filepath);
System.IO.Stream stream = null;
试试
{
//将文件打开到流中.
stream =新的FileStream(filepath,System.IO.FileMode.Open,System.IO.FileAccess.Read,System.IO.FileShare.Read);
//读取的总字节数:
long bytesToRead = stream.Length;
Response.ContentType =应用程序/八位字节流";
Response.AddHeader("Content-Disposition","attachment; filename =" + filename);
//从一小部分读取流中的字节.
while(bytesToRead> 0)
{
//确保客户端仍处于连接状态.
如果(Response.IsClientConnected)
{
//将数据读入缓冲区并写入
//输出流.
byte []缓冲区=新的Byte [10000];
int length = stream.Read(buffer,0,10000);
Response.OutputStream.Write(buffer,0,length);
Response.Flush();
//我们已经读取了一些字节..需要读取
//仅剩下.
bytesToRead = bytesToRead-长度;
}
其他
{
//如果用户不再连接,则退出循环.
bytesToRead = -1;
}
}
}
catch(ex ex例外)
{
Response.Write(ex.Message);
//发生错误..
}
终于
{
如果(流!=空)
{
stream.Close();
}
}

任何建议将不胜感激.实际上,最令人惊讶的部分是,如果我使用google chrome作为浏览器,则文件将以正确的格式下载,但是如果我使用IE或Mozilla firefox,则会下载未知格式的文件.

I have ran into a situation where im able to download a file by specifying the file path but the issue is that the file is download in a unknown format. The code below shows the downloading process:

if (e.CommandName == "ViewFiles")
{

int index = Convert.ToInt32(e.CommandArgument);

GridViewRow row = gvunclassified.Rows[index];

string division = row.Cells[4].Text;

string filenames = row.Cells[1].Text;

string paths = @"NewFolder1" + "\\" + division + "\\" + "UnClassified" + "\\" + filenames;
string drive = @"C:\Website2\RecordsManagement";
string temppath = Path.Combine(drive, paths);


// The file path to download.

string filepath = temppath;

// The file name used to save the file to the client''s system..

string filename = Path.GetFileName(filepath);
System.IO.Stream stream = null;
try
{
// Open the file into a stream.
stream = new FileStream(filepath, System.IO.FileMode.Open, System.IO.FileAccess.Read, System.IO.FileShare.Read);
// Total bytes to read:
long bytesToRead = stream.Length;
Response.ContentType = "application/octet-stream";
Response.AddHeader("Content-Disposition", "attachment; filename=" + filename);
// Read the bytes from the stream in small portions.
while (bytesToRead > 0)
{
// Make sure the client is still connected.
if (Response.IsClientConnected)
{
// Read the data into the buffer and write into the
// output stream.
byte[] buffer = new Byte[10000];
int length = stream.Read(buffer, 0, 10000);
Response.OutputStream.Write(buffer, 0, length);
Response.Flush();
// We have already read some bytes.. need to read
// only the remaining.
bytesToRead = bytesToRead - length;
}
else
{
// Get out of the loop, if user is not connected anymore..
bytesToRead = -1;
}
}
}
catch (Exception ex)
{
Response.Write(ex.Message);
// An error occurred..
}
finally
{
if (stream != null)
{
stream.Close();
}
}

Any suggestion would be highly appreciated. Actually the most surprising part is that if I use google chrome as my browser then the file is downloaded in the right format but an unknown format file is download if I use IE or Mozilla firefox.

推荐答案

代码以下载文件

Code to Download the File

Response.ClearContent();
               Response.AddHeader("Content-Disposition", "attachment; filename=" + filename);
               BinaryWriter bw = new BinaryWriter(Response.OutputStream);
               bw.Write(fileData);
               bw.Close();
               Response.ContentType = ReturnExtension(ext);
               Response.End();



用于扩展的功能,使功能通用,以便您可以在整个项目中使用它,下面的功能是我从Code Project获得的,有些来源我现在不记得了,现在在我的项目中使用它,它非常适合我在任何浏览器中



Function used to get extension , make a function as common so u can use it in youer entire project , the below function i got it from Code Project some source i dont remember it now , and i am using it in my project it works perfectly for me in any browser

public string ReturnExtension(string fileExtension)
    {
        switch (fileExtension)
        {
            case ".htm":
            case ".html":
            case ".log":
                return "text/HTML";
            case ".txt":
                return "text/plain";
            case ".doc":
                return "application/ms-word";
            case ".tiff":
            case ".tif":
                return "image/tiff";
            case ".asf":
                return "video/x-ms-asf";
            case ".avi":
                return "video/avi";
            case ".zip":
                return "application/zip";
            case ".xls":
            case ".csv":
                return "application/vnd.ms-excel";
            case ".gif":
                return "image/gif";
            case ".jpg":
            case "jpeg":
                return "image/jpeg";
            case ".bmp":
                return "image/bmp";
            case ".wav":
                return "audio/wav";
            case ".mp3":
                return "audio/mpeg3";
            case ".mpg":
            case "mpeg":
                return "video/mpeg";
            case ".rtf":
                return "application/rtf";
            case ".asp":
                return "text/asp";
            case ".pdf":
                return "application/pdf";
            case ".fdf":
                return "application/vnd.fdf";
            case ".ppt":
                return "application/mspowerpoint";
            case ".dwg":
                return "image/vnd.dwg";
            case ".msg":
                return "application/msoutlook";
            case ".xml":
            case ".sdxl":
                return "application/xml";
            case ".xdp":
                return "application/vnd.adobe.xdp+xml";
            default:
                return "application/octet-stream";
        }
    }


让我知道它有效


Let me know of it works


这篇关于从目录下载文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆