一、主题要是把Winform客户端上传的图片(doc,excel,txt等小文件)上传到远程文件服务器上。
方案有很多种,比如用TCP、Socket、FTP,但这些方式控制不好,很容易失败,要么工程量大,费时费力。
为了快速建立模型,采用客户端Winform + IIS服务器端方式。效果图如下:
二、源代码:
三、解决:远程服务器返回错误: (401,405)
出现这个问题,在上传文件至服务器时,大部分人使用代码都是WebClient类,采用上传和下载,刚开始下载可以,但上传始终没有权限。上传代码类似:
private void UpLoadFile(string fileNamePath, string serverFileURL)
{
// 创建WebClient实例
WebClient myWebClient = new WebClient();
myWebClient.Credentials = CredentialCache.DefaultCredentials;
// 要上传的文件
FileStream fs = new FileStream(fileNamePath, FileMode.Open, FileAccess.Read);
BinaryReader r = new BinaryReader(fs);
try
{
//使用UploadFile方法可以用下面的格式
byte[] postArray = r.ReadBytes((int)fs.Length);
Stream postStream = myWebClient.OpenWrite(serverFileURL, "PUT");
if (postStream.CanWrite)
{
postStream.Write(postArray, 0, postArray.Length);
}
postStream.Close();
}
catch
{
//MessageBox.Show("文件上传失败,请稍候重试~");
}
}
出现的根本原因时,iis服务器不允许,随意写入文件。
如果解决 401问题,请参考 : http://www.pageadmin.net/article/2015/1074.html ,解决 405,主要是打开IIS ”PUT“ 指令。
1、Win7下默认WebClient是手动启动,这个需要设置成自动启动,为启动状态;
2、上传文件的文件夹有写入权限,匿名,所有人都可以写入;
3、在IIS 上 开启WebDav,并设置规则
经常上述调整,使用下载没有问题,下载代码如下:
/// <summary>
/// 下载服务器文件至客户端(不带进度条)
/// </summary>
/// <param name="strUrlFilePath">要下载的Web服务器上的文件地址(全路径 如:http://www.dzbsoft.com/test.rar)</param>
/// <param name="Dir">下载到的目录(存放位置,机地机器文件夹)</param>
/// <returns>True/False是否上传成功</returns>
public bool WebClientDownLoadFile(string strUrlFilePath, string strLocalDirPath)
{
// 创建WebClient实例
WebClient client = new WebClient();
//被下载的文件名
string fileName = strUrlFilePath.Substring(strUrlFilePath.LastIndexOf("/"));
//另存为的绝对路径+文件名
string Path = strLocalDirPath + fileName;
try
{
WebRequest myWebRequest = WebRequest.Create(strUrlFilePath);
client.DownloadFile(strUrlFilePath, Path);
return true;
}
catch (Exception exp)
{
client.Dispose();
return false;
}
}
但上传仍然不能实现。最终采用了另外一种上传代码,客户端把流传给服务器端,服务器端自己下载。也是本次记录的主要目的,上述源码中已经实现了。代码全部开源。
上传代码修改为:
/// <summary>
/// 上传
/// </summary>
/// <param name="ServerUrl">服务器地址</param>
/// <param name="LocationFilePath">本地图片全路径</param>
/// <param name="SavePath">上传成功返回保存的路径</param>
/// <param name="AllowFormat">允许上传图片的后缀名,* 和空值都表示所有图片格式,多个请用,隔开,例如:.gif,.png,.jpg,.bmp</param>
/// <param name="progressBar">进度控件</param>
/// <returns>返回:-2=图片格式有误,-1=服务器地址 或 本地图片全路径为空 0=上传失败 1=上传成功</returns>
public int UpLoad(string ServerUrl, string LocationFilePath, out string SavePath, string AllowFormat, System.Windows.Forms.ProgressBar progressBar)
{
SavePath = string.Empty;
if (string.IsNullOrEmpty(ServerUrl) || string.IsNullOrEmpty(LocationFilePath))
return -1;
AllowFormat = string.IsNullOrEmpty(AllowFormat) == true ? "*" : AllowFormat;
//获取后缀名
string Suffix = LocationFilePath.Substring(LocationFilePath.LastIndexOf(".")).Trim().ToLower();
string[] strformat = ".gif,.png,.jpeg,.jpg,.bmp".Split(",".ToCharArray());
if (!strformat.Contains(Suffix))
return -2;
//检验图片格式
if (AllowFormat != "*")
{
string[] strformat2 = AllowFormat.Split(",".ToCharArray());
if (!strformat2.Contains(Suffix))
return -2;
}
string year = DateTime.Now.Year.ToString();
string filename = DateTime.Now.ToString("yyyyMMddHHmmssfffff") + Suffix;
int result = Upload_Request(ServerUrl, LocationFilePath, filename, progressBar);
if (result == 1)
SavePath = "/upload/" + year + "/" + filename;
return result;
}
服务器端代码:
public partial class img : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (Request.Files.Count > 0)
{
try
{
string savePath = Server.MapPath("~/upload/" + DateTime.Now.Year.ToString() + "/");
if (!Directory.Exists(savePath)) Directory.CreateDirectory(savePath);
HttpPostedFile file = Request.Files[0];
string filePath = savePath + "\\" + file.FileName;
file.SaveAs(filePath);
Response.Write("Success");
}
catch
{
Response.Write("Error");
}
}
else
{
Response.Write("Error1");
}
}
}
收藏:Web 批量上传图片的特效代码,采用asp.net mvc 模式,效果图如下,需要的源码的可以下载参考。 MVC 图片批量上传.rar