如何上传和下载文件

时间:2011-07-08 09:23:02

标签: asp.net

我喜欢在我的项目中上传文件。当我单击上传按钮时,文件应存储在客户端系统中,文件名和路径应存储在数据库中。当我单击下载按钮时,应根据我存储在数据库中的文件名和路径下载它。进行更改后,应将其作为不同的文件名上传,不会影响以前的文件内容。如果此流程有任何代码,请发送给我。

提前致谢

2 个答案:

答案 0 :(得分:1)

要上传文件,请使用input类型file,然后在服务器上进行相应处理。这是一个完整的tutorial on CodePlex,它完全符合您的要求。

警告不要在生产中使用他们的代码。刚注意到一些安全风险,但无论如何,使用它来理解该过程,然后弄清楚如何避免sql注入和可能的溢出。

以下是MSDN上关于File Uploading in ASP.NET 2.0的另一篇精彩文章。

答案 1 :(得分:0)

string FolderPath = "yourpath";

string FileName = "Namefile";

string FilePath = Server.MapPath("~/" + FileName);

string Extension = Path.GetExtension(FileName);

Response.ContentType = "Application/x-msexcel";
Response.AppendHeader("Content-Disposition", "attachment; filename=" + FileName + "");

// Write the file to the Response
const int bufferLength = 10000;
byte[] buffer = new Byte[bufferLength];
int length = 0;
Stream download = null;
try {
    download = new FileStream(Server.MapPath("~/" + FileName),
                                FileMode.Open,
                                FileAccess.Read);
    do {
        if (Response.IsClientConnected) {
            length = download.Read(buffer, 0, bufferLength);
            Response.OutputStream.Write(buffer, 0, length);
            buffer = new Byte[bufferLength];
        }
        else {
            length = -1;
        }
    }
    while (length > 0);
    Response.Flush();
    Response.End();
}
finally {
    if (download != null)
        download.Close();
}