服务器之家

服务器之家 > 正文

C#实现文件上传与下载功能实例

时间:2021-12-13 14:45     来源/作者:pan_junbiao

最近学习了 C#实现文件上传与下载,现在分享给大家。

1、C#文件上传

创建MyUpload.htm页面,用于测试

?
1
2
3
4
5
<form name="form1" method="post" action="UploadFile.aspx" id="form1"
enctype="multipart/form-data">
  <input type="file" id="txtFile" name="picfile" /></br>
  <input type="submit" value="上传" />
</form>

创建UploadFile.aspx文件,在UploadFile.aspx.cs键入如下代码:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
Random rnd = new Random();              //产生随机数
private string _directory = @"/File/UploadFile";   //目录
protected void Page_Load(object sender, EventArgs e)
{
  try
  {
    if (RequestFilesCount > 0)
    {
      //判断文件大小
      int length = RequestFiles[0]ContentLength;
      if (length > 1048576)
      {
        ResponseWrite("文件大于1M,不能上传");
        return;
      }
 
      string type = RequestFiles[0]ContentType;
      string fileExt = PathGetExtension(RequestFiles[0]FileName)ToLower();
      //只能上传图片,过滤不可上传的文件类型
      string fileFilt = "gif|jpg|php|jsp|jpeg|png|";
      if (fileFiltIndexOf(fileExt) <= -1)
      {
        ResponseWrite("对不起!请上传图片!!");
        return;
      }
      else
      {
        string fileName = ServerMapPath(_directory) + "\\" + DateTimeNowToString("yyyyMMddHHmmssfff") + rndNext(10, 99)ToString() + fileExt;
        RequestFiles[0]SaveAs(fileName);
        ResponseWrite("上传成功!");
      }
    }
  }
  catch
  {
    throw new Exception();
  }
}

2 、C#文件下载

创建DownloadFile.aspx,在DownloadFile.aspx.cs键入如下方法:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
/// <summary>
/// C#文件下载
/// </summary>
/// <param name="filename"></param>
public void MyDownload(string filename)
{
 
  string path = ServerMapPath("/File/"+filename);
  if(!FileExists(path))
  {
    ResponseWrite("对不起!文件不存在!!");
    return;
  }
  SystemIOFileInfo file = new SystemIOFileInfo(path);
  string fileFilt="asp|aspx|php|jsp|ascx|config|asa|"; //不可下载的文件,务必要过滤干净
  string fileName = fileName;
  string fileExt = fileNameSubstring(filenameLastIndexOf(""))Trim()ToLower();
  if(fileFiltIndexOf(fileExt)!=-1)
  {
    ResponseWrite("对不起!该类文件禁止下载!!");
  }
  else
  {
    ResponseClear();
    ResponseAddHeader("Content-Disposition", "attachment; filename=" + HttpUtilityUrlEncode(fileName));
    ResponseAddHeader("Content-Length", fileLengthToString());
    ResponseContentType = GetContentType(HttpUtilityUrlEncode(fileExt));
    ResponseWriteFile(fileFullName);
    ResponseEnd();
  }
}
 
/// <summary>
/// 获取下载类型
/// </summary>
/// <param name="fileExt"></param>
/// <returns></returns>
public string GetContentType(string fileExt)
{
  string ContentType;
  switch (fileExt)
  {
    case "asf":
      ContentType = "video/x-ms-asf"; break;
    case "avi":
      ContentType = "video/avi"; break;
    case "doc":
      ContentType = "application/msword"; break;
    case "zip":
      ContentType = "application/zip"; break;
    case "xls":
      ContentType = "application/vndms-excel"; break;
    case "gif":
      ContentType = "image/gif"; break;
    case "jpg":
      ContentType = "image/jpeg"; break;
    case "jpeg":
      ContentType = "image/jpeg"; break;
    case "wav":
      ContentType = "audio/wav"; break;
    case "mp3":
      ContentType = "audio/mpeg3"; break;
    case "mpg":
      ContentType = "video/mpeg"; break;
    case "mepg":
      ContentType = "video/mpeg"; break;
    case "rtf":
      ContentType = "application/rtf"; break;
    case "html":
      ContentType = "text/html"; break;
    case "htm":
      ContentType = "text/html"; break;
    case "txt":
      ContentType = "text/plain"; break;
    default:
      ContentType = "application/octet-stream";
      break;
  }
  return ContentType;
}

*如何获取现有文件的ContentType属性

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
/// <summary>
/// 获取现有文件的ContentType属性
/// </summary>
/// <param name="filename"></param>
/// <returns></returns>
public string GetFileContentType(string filename)
{
  string[] array = filenameSplit('');
  string result = stringEmpty;
  string suffix = "" + array[arrayLength - 1];
  MicrosoftWinRegistryKey rg = MicrosoftWinRegistryClassesRootOpenSubKey(suffix);
  object obj = rgGetValue("Content Type");
  result = obj != null ? objToString() : stringEmpty;
  rgClose();
  return result;
}

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持服务器之家。

原文链接:http://blog.csdn.net/pan_junbiao/article/details/7185382

标签:

相关文章

热门资讯

yue是什么意思 网络流行语yue了是什么梗
yue是什么意思 网络流行语yue了是什么梗 2020-10-11
背刺什么意思 网络词语背刺是什么梗
背刺什么意思 网络词语背刺是什么梗 2020-05-22
2020微信伤感网名听哭了 让对方看到心疼的伤感网名大全
2020微信伤感网名听哭了 让对方看到心疼的伤感网名大全 2019-12-26
2021年耽改剧名单 2021要播出的59部耽改剧列表
2021年耽改剧名单 2021要播出的59部耽改剧列表 2021-03-05
苹果12mini价格表官网报价 iPhone12mini全版本价格汇总
苹果12mini价格表官网报价 iPhone12mini全版本价格汇总 2020-11-13
返回顶部