2023年7月3日发(作者:)
C# WinForm 文件上传下载 收藏
/**//**//**////
/// WebClient上传文件至服务器
///
/// 文件名,全路径格式
/// 服务器文件夹路径
/// 是否需要修改文件名,这里默认是日期格式
///
public static bool UploadFile(string localFilePath, string serverFolder,bool reName)
......{
string fileNameExt, newFileName, uriString;
if (reName)
......{
fileNameExt = ing(dexOf(".") + 1);
newFileName = ng("yyMMddhhmmss") + fileNameExt;
}
else
......{
newFileName = ing(dexOf("")+1);
}
if (!th("/") && !th(""))
......{
serverFolder = serverFolder + "/";
}
uriString = serverFolder + newFileName; //服务器保存路径
/**//**//**//// 创建WebClient实例
WebClient myWebClient = new WebClient();
tials = tCredentials;
// 要上传的文件
FileStream fs = new FileStream(newFileName, , );
BinaryReader r = new BinaryReader(fs);
try
......{
//使用UploadFile方法可以用下面的格式
//File(uriString,"PUT",localFilePath);
byte[] postArray = tes((int));
Stream postStream = ite(uriString, "PUT");
if (te)
......{ (postArray, 0, );
}
else
......{
("文件目前不可写!");
}
();
}
catch
......{
//("文件上传失败,请稍候重试~");
return false;
}
return true;
}
/**//**//**////
/// 下载服务器文件至客户端
///
/// 被下载的文件地址
/// 另存放的目录
public static bool Download(string uri, string savePath)
......{
string fileName; //被下载的文件名
if (f("") > -1)
......{
fileName = ing(dexOf("") + 1);
}
else
......{
fileName = ing(dexOf("/") + 1);
}
if (!th("/") && !th(""))
......{
savePath = savePath + "/";
}
savePath += fileName; //另存为的绝对路径+文件名
WebClient client = new WebClient(); try
......{
adFile(uri, savePath);
}
catch
......{
return false;
}
return true;
}
************************************************
命名空间
;
;
上传IIS虚拟目录需要给写入权限,下载可能需要匿名访问权限。
本文来自CSDN博客,转载请标明出处:/wxg22526451/archive/2008/03/24/
字号:大 中 小
using System;
using ;
using ;
namespace leo
{
///
/// 文件上传类
/// 作者:leo
/// 制作时间:2006-2-13 最后修改于2007-6-25
/// public class UploadFile
{
public UploadFile(HttpPostedFile PostedFile)
{
FileObj = PostedFile;
}
private HttpPostedFile FileObj;
private int maxSize = 150 * 1024;
private string filesType = ".jpeg|.jpg|.gif";
private bool oldFileName = false;
private string filesPath = "";
private string Eror = "";
private int errorNum = 0;
private string savaFileName = "";
//属性区
public int MaxSizeKB
{
get{ return maxSize / 1024; }
set{ maxSize = value * 1024;}
}
public string FilesType
{
get{ return filesType; }
//默认150KB
//默认文件类型
//是否采用原文件名
//设置文件夹路径
//错误信息
//错误码
//上传成功后的文件名称
set{ filesType = r();}
}
public string FilesPath
{
get{ return filesPath; }
set{ filesPath = value;}
}
public string SavaFileName
{
get{ return savaFileName; }
set{ savaFileName = value;}
}
public string SaveEror
{
get{ return Eror; }
}
public int ErrorNum
{
get { return errorNum; }
}
public bool OldFileName
{
get{ return oldFileName; } set{ oldFileName = value;}
}
//方法区
private string GetNewFileName(string FlieExtension)
{
Random rd = new Random();
int rnum = (100, 999);
string dt = ng("yyyyMMddhhmmss");
return dt + ng() + FlieExtension;
}
public bool SaveFile()
{
if (FileObj != null)
{
try
{
string strFileURLName = me;
//上传文件原URL
string strFileName = eName(strFileURLName); //上传文件原名
string strFlieExtension = ension(strFileURLName).ToLower(); //上传文件原扩展名
if (tLength == 0)
{
Eror = "您上传的文件为空";
errorNum = 2;
return false;
}
if (tLength > maxSize)
{
Eror = "上传文件超过限定大小";
errorNum = 3;
return false;
}
string[] fType = ('|');
bool ok = false;
for (int i = 0; i < ; i++)
{
if (fType[i] == strFlieExtension)
ok = true;
}
if (!ok)
{
Eror = "上传文件类型不是程序允许的类型"; errorNum = 4;
return false;
}
if(!(filesPath))
{
Eror = "文件存储的目录不存在";
errorNum = 5;
return false;
}
string NewFileName;
if (!oldFileName)
{
NewFileName = GetNewFileName(strFlieExtension);
}
else
NewFileName = strFileName;
try
{
(e(filesPath,NewFileName));
} catch
{
Eror = "存储文件时发生错误,可能是该目录没有权限";
errorNum = 6;
return false;
}
savaFileName = NewFileName;
Eror = "";
errorNum = 0;
return true;
}
catch(Exception e)
{
Eror = ng();
errorNum = 9;
return false;
}
}
else
{
Eror = "没有文件被上传";
errorNum = 1; return false;
}
}
}
}
C# WinForm 文件上传下载 (附源码)
**////
/// WebClient上传文件至服务器
///
/// 文件名,全路径格式
/// 服务器文件夹路径
private void UpLoadFile(string fileNamePath,string uriString)
{
//string fileName = ing(dexOf("") + 1);
NewFileName = ng("yyMMddhhmmss")
ng()
ing(dexOf("."));
string fileNameExt = ing(dexOf(".") + 1);
if(th("/") == false) uriString = uriString + "/";
uriString = uriString + NewFileName;
/**//// 创建WebClient实例
WebClient myWebClient = new WebClient();
tials = tCredentials;
// 要上传的文件
FileStream fs = new FileStream(fileNamePath, , );
//FileStream fs = OpenFile();
BinaryReader r = new BinaryReader(fs);
try
{
//使用UploadFile方法可以用下面的格式
//File(uriString,"PUT",fileNamePath);
byte[] postArray = tes((int));
+
+ Stream postStream = ite(uriString,"PUT");
if(te)
{
(postArray,0,);
}
else
{
("文件目前不可写!");
}
();
}
catch
{
("文件上传失败,请稍候重试~");
}
}
/**////
/// 下载服务器文件至客户端
///
/// 被下载的文件地址,绝对路径
/// 另存放的目录
public void Download(string URL,string Dir)
{
WebClient client = new WebClient();
string fileName = ing(dexOf("") + 1); //被下载的文件名
string Path = Dir+fileName; //另存为的绝对路径+文件名
try
{
WebRequest myre=(URL);
}
catch
{
//(e,"Error");
}
try
{
adFile(URL,Path);
}
catch
{
//(e,"Error");
}
}
/*---------------------------------------------
* 黑白之间
* gxian22@
* 最后修改日期:2008年9月9日21:39:41
*UploadFile ufud = new UploadFile();
*
* ze = 250;
* 默认为 200KB 如要上传大于6兆以上图片要在 配置<> executionTimeout="60"/>> * *FileList = "/UploadFiles"; //默认为 UploadFile 文件夹 * *--------不压缩则不设置--------- *=1 //1为缩略图 *th = 250;//缩略尺寸 *th = 250;//缩略尺寸 *------------------------------- *eFileNameMode = 2;//更改上传文件名字有三种(0 原始的 不更改 ,1 全局唯一标识型,2 时间 ) 默认全局唯一标识型 类型 *ploadExtension = ".gif,.jpg,.png,.html"; *loads(File);// Fil(上传控件名称).PostedFile * * *(dAndError)//返回成功或错误文字信息 *(ode) //返回成功或错误代码 0成功 1文件太大 2文件太小 3格式不正确 4其他错误 *(FilePath) //返回上传文件路径 ---------------------------------------------*/ using System; using ; using g; namespace Common { /// /// 支持上传缩略图、更改图片名、自定义上传文件格式和文件大小。 /// public class UploadFile { private string uploadfilelist = "UploadFile"; private int userid = 0; private int filesize = 200;//200K private string filesuploadextension = ".gif,.jpg,.png"; private string returnfilepath = "--"; private string succeedanderror = null; private int errorcode = 0; private int rewritefilenamemode = 1; private int imgheight = 120, imgwidth = 120; private int reduce = 0; /// /// 上传图片默认原始大小,1为缩略图同时你要设置缩略 宽:ImgWidth=?,高: ImgHidth=? /// public int Reduce { get { return reduce; } set { reduce = value; } } /// /// 图片缩略宽度大小 默认 120 /// public int ImgWidth { get { return imgwidth; } set { imgwidth = value; } } /// /// 图片缩略高大小 默认 120 /// public int ImgHidth { get { return imgheight; } set { imgheight = value; } } /// /// 上传文件存放目录 /// public string UploadFileList { get { return uploadfilelist; } set { uploadfilelist = value; } } /// /// 更改上传文件名字有三种(0 原始的 不更改 ,1 全局唯一标识型,2 时间 ) 默认全局唯一标识型 类型 /// public int RewriteFileNameMode { get { return rewritefilenamemode; } set { rewritefilenamemode = value; } } /// /// 上传用户ID /// public int UserID { get { return userid; } set { userid = value; } } /// /// 文件上传大小 默认为200K /// public int FileSize { get { return filesize; } set { filesize = value; } } /// /// 设置允许上传文件类型, 默认为(.gif,.jpg,.txt) /// public string FilesUploadExtension { get { return filesuploadextension; } set { filesuploadextension = value; } } /// /// 返回上传文件路径 /// public string ReturnFilePath { get { return returnfilepath; } set { returnfilepath = value; } } /// /// 成功 或 错误信息 /// public string SucceedAndError { get { return succeedanderror; } set { succeedanderror = value; } } /// /// 返回错误编号 0成功 1文件太大 2文件太小 3格式不正确 4其他错误 /// public int ErrorCode { get { return errorcode; } set { errorcode = value; } } /// /// /// 上传控件名称 public void FileUploads(stedFile HttpPflie) { oriImg;//, newImg; int ImageHeight, ImageWidth; string strFileExt = ension(me).ToString().ToLower(); //提取上传文件 扩展名。 if ("".Equals(strFileExt)) { SucceedAndError = ("不能上传的文件,允许上传格式({0})", FilesUploadExtension); ErrorCode = 3; ReturnFilePath = "--"; return; } int ifcheck = f(r()); //是否为允许上传的格式 if (ifcheck < 0) { SucceedAndError = ("不能上传的文件,允许上传格式{0}", FilesUploadExtension); ErrorCode = 3; ReturnFilePath = "--"; return; } int FileUploadSize = FilSize(tLength); //上传文件大小 if (FileUploadSize <= 0) { SucceedAndError = "文件不得小于0KB"; ErrorCode = 2; ReturnFilePath = "--"; return; } if (FileUploadSize >= FileSize) { SucceedAndError = ("文件不得大于{0},您超过了{1}", KBStr(FileSize), KBStr(FileUploadSize - FileSize)); ErrorCode = 1; ReturnFilePath = "--"; return; } if (ifcheck >= 0 && FileUploadSize > 0 && FileUploadSize < FileSize) { string NewFileName = null, filelist = null; //生成文件名 try { #region ----------生成上传文件名---------- switch (RewriteFileNameMode) { case 2://时间型文件名 DateTime date = ; string FileName ng("MM") + ng = ng("yyyy") + ("dd"); FileName += ng("HH") + ng("mm") + ng("ss"); Random rnd = new Random(); double rndNum = uble() * 10000; NewFileName = ng().Substring(0, ng().LastIndexOf(".")) + strFileExt; //生成新的文件名 break; case 1: NewFileName strFileExt; break; case 0: NewFileName ing(dexOf("/") > -1 ? = = d().ToString("b") + FileName + dexOf("/") : dexOf("")).Replace("/", "").Replace("", ""); break; } #endregion //创建文件夹 将上传的文件按月分开存放。 string datafile Time().ToString("yyyy") + "-" + Time ().ToString("MM"); filelist e(".", "") + "/"; string h(filelist); path = = UploadFileList + "/" + datafile + "/" + = if (!(path)) Directory(path);//生成文件保存目录 #region ----------生成缩略图并上传---------- if (Reduce == 1 ('/')[0].Equals("image"))//tType是否为 图片文件 { oriImg ream(tream); if ( / >= ImgWidth / ImgHidth) { if ( > ImgHidth) { ImageWidth = ImgWidth; ImageHeight = 32( * ImgWidth) / ; } else { ImageWidth = ; = && ImageHeight = ; } } else { if ( > ImgWidth) { ImageWidth = 32( * ImgHidth) / ; ImageHeight = ImgHidth; } else { ImageWidth = ; ImageHeight = ; } } //----------------------高质量--------------------- Bitmap newImg = new Bitmap(ImageWidth, ImageHeight); //以缩略图的宽高 创建位图对象 Graphics //创建Graphics对 象,用于缩略图的图像的绘制 olationMode ; //获取或设置与此 Graphics 对象关联的插补模式。指定高质量插值法。 ingMode ality; //指定高质量、低 速度呈现。 = = g = age(newImg); (arent); //清除整个绘图面 并以透明色填充。 age(ream(tream), new Rectangle(0, 0, ImageWidth, ImageHeight), new Rectangle(0, 0, , ), );//缩略图绘制 // newImg = ImageHeight, null, new (0)); //低质 量 switch (strFileExt) { case ".jpg": (path + "/" + NewFileName, ); break; case ".gif": (path + "/" + NewFileName, ); break; case ".png": (path + "/" + NewFileName, ); break; default: (path + "/" + NewFileName, ); break; } e(); e(); } #endregion #region ----------原始尺寸图片上传---------- if (!('/')[0].Equals("image") || Reduce == 0) { path = path + "/" + NewFileName; (path); } #endregion SucceedAndError = "文件上传成功"; mbnailImage(ImageWidth, ErrorCode = 0; ReturnFilePath = filelist + NewFileName; } catch (Exception e){ SucceedAndError = e; ErrorCode = 4; } finally{ //break; } } } private static int FilSize(int imgSize) { return ((imgSize / 1024) * 100) / 100; } } }
发布者:admin,转转请注明出处:http://www.yc00.com/xiaochengxu/1688384500a130010.html
评论列表(0条)