C#实现文件上传与下载功能实例
最近学习了C#实现文件上传与下载,现在分享给大家。
1、C#文件上传
创建MyUpload.htm页面,用于测试
<formname="form1"method="post"action="UploadFile.aspx"id="form1" enctype="multipart/form-data"> <inputtype="file"id="txtFile"name="picfile"/></br> <inputtype="submit"value="上传"/> </form>
创建UploadFile.aspx文件,在UploadFile.aspx.cs键入如下代码:
Randomrnd=newRandom();//产生随机数
privatestring_directory=@"/File/UploadFile";//目录
protectedvoidPage_Load(objectsender,EventArgse)
{
try
{
if(RequestFilesCount>0)
{
//判断文件大小
intlength=RequestFiles[0]ContentLength;
if(length>1048576)
{
ResponseWrite("文件大于1M,不能上传");
return;
}
stringtype=RequestFiles[0]ContentType;
stringfileExt=PathGetExtension(RequestFiles[0]FileName)ToLower();
//只能上传图片,过滤不可上传的文件类型
stringfileFilt="gif|jpg|php|jsp|jpeg|png|";
if(fileFiltIndexOf(fileExt)<=-1)
{
ResponseWrite("对不起!请上传图片!!");
return;
}
else
{
stringfileName=ServerMapPath(_directory)+"\\"+DateTimeNowToString("yyyyMMddHHmmssfff")+rndNext(10,99)ToString()+fileExt;
RequestFiles[0]SaveAs(fileName);
ResponseWrite("上传成功!");
}
}
}
catch
{
thrownewException();
}
}
2、C#文件下载
创建DownloadFile.aspx,在DownloadFile.aspx.cs键入如下方法:
///<summary>
///C#文件下载
///</summary>
///<paramname="filename"></param>
publicvoidMyDownload(stringfilename)
{
stringpath=ServerMapPath("/File/"+filename);
if(!FileExists(path))
{
ResponseWrite("对不起!文件不存在!!");
return;
}
SystemIOFileInfofile=newSystemIOFileInfo(path);
stringfileFilt="asp|aspx|php|jsp|ascx|config|asa|";//不可下载的文件,务必要过滤干净
stringfileName=fileName;
stringfileExt=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>
///<paramname="fileExt"></param>
///<returns></returns>
publicstringGetContentType(stringfileExt)
{
stringContentType;
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;
}
returnContentType;
}
*如何获取现有文件的ContentType属性
///<summary>
///获取现有文件的ContentType属性
///</summary>
///<paramname="filename"></param>
///<returns></returns>
publicstringGetFileContentType(stringfilename)
{
string[]array=filenameSplit('');
stringresult=stringEmpty;
stringsuffix=""+array[arrayLength-1];
MicrosoftWinRegistryKeyrg=MicrosoftWinRegistryClassesRootOpenSubKey(suffix);
objectobj=rgGetValue("ContentType");
result=obj!=null?objToString():stringEmpty;
rgClose();
returnresult;
}
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持毛票票。