public class FileUploadArgs : EventArgs
{
public string FileName { get; set; }
public Exception Ex { get; set; }
}
public class FileUploader
{ #region Member Variables /// <summary>
/// The web client used to asynchronously upload data.
/// </summary>
private WebClient webClient = new WebClient(); /// <summary>
/// Acts as an index in the file array and is used by multiple event
/// handlers.
///
/// Upload process starts with currentFileIndex = 0, and when the
/// first file is successfully uploaded, the index is incremented.
///
/// When the index is gets above the length of the array, then it
/// is evident that all the files have been uploaded.
///
/// </summary>
private int currentFileIndex; FileInfo[] _fileInfo;
string[] reNameFiles;
string folderName; #endregion
#region Business Logic public FileUploader()
{
webClient.OpenWriteCompleted += webClient_OpenWriteCompleted;
webClient.WriteStreamClosed += webClient_WriteStreamClosed;
}
~FileUploader()
{
webClient.OpenWriteCompleted -= webClient_OpenWriteCompleted;
webClient.WriteStreamClosed -= webClient_WriteStreamClosed;
}
private void webClient_OpenWriteCompleted(object s, OpenWriteCompletedEventArgs e)
{
//Make sure that the file to be uploaded is not null.
if (_fileInfo[currentFileIndex] != null)
{
//Create a file upload argument to pass to events.
FileUploadArgs fileUploadArgs = new FileUploadArgs() { FileName = _fileInfo[currentFileIndex].Name };
try
{
if (OnFileUploadStarted != null)
{
OnFileUploadStarted(this, fileUploadArgs);
} //Open a file stream corresponding to the
Stream fileStream = _fileInfo[currentFileIndex].OpenRead();
PushData(fileStream, e.Result); //Close the streams.
e.Result.Close();
fileStream.Close();
fileStream.Dispose();
}
catch (Exception ex)
{
if (OnFileUploadError != null)
{
fileUploadArgs.Ex = new Exception("此文件正在使用,请关闭后重新选择!", ex);
OnFileUploadError(this, fileUploadArgs);
}
} }
}
private void webClient_WriteStreamClosed(object s, WriteStreamClosedEventArgs e)
{
//ToDo: Output a helpful error.
if (e.Error == null)
{
//Create a file upload argument to pass to events.
FileUploadArgs fileUploadArgs = new FileUploadArgs() { FileName = _fileInfo[currentFileIndex].Name }; if (OnFileUploadCompleted != null)
{
OnFileUploadCompleted(this, fileUploadArgs);
} currentFileIndex++; //Try to find the next null object.
while (currentFileIndex < _fileInfo.Length && _fileInfo[currentFileIndex] == null)
currentFileIndex++; //Check to see if there are more files waiting to be uploaded.
if (currentFileIndex < _fileInfo.Length)
{
Uri nextUri = GetUri(_fileInfo[currentFileIndex], reNameFiles[currentFileIndex], folderName); //Start another upload.
webClient.OpenWriteAsync(nextUri); }
//All file uploads are complete.
else
{
if (OnAllFilesUploadCompleted != null)
{
OnAllFilesUploadCompleted(this, fileUploadArgs);
}
}
}
}
/// <summary>
/// This method should only be used for uploading single files.
/// </summary>
/// <param name="fileInfo">The file to upload</param>
/// <param name="projectName">The server side folder where to upload the file.</param>
public void UploadFile(FileInfo fileInfo, string reNameFile, string folderName)
{
UploadFiles(new FileInfo[] { fileInfo }, new string[] { reNameFile }, folderName);
} public void UploadFiles(FileInfo[] fileInfo, string[] reNameFiles, string folderName)
{ //ToDo: Throw an error when fileInfo is null.
if (fileInfo == null)
return; _fileInfo = fileInfo; this.reNameFiles = reNameFiles;
this.folderName = folderName; currentFileIndex = ; //Find the first non-null file info.
while (currentFileIndex < fileInfo.Length && fileInfo[currentFileIndex] == null)
currentFileIndex++; //If all files were null, exit the method.
if (currentFileIndex == fileInfo.Length)
{
//ToDo: might need an exception here. On the other, silent exit is not
//such a bad thing, since if all files are null then basically without
//uploading any files, the method is done.
return;
} //Start file upload from that first non-null file.
Uri uri = GetUri(fileInfo[currentFileIndex], reNameFiles[currentFileIndex], folderName); webClient.OpenWriteAsync(uri);
} #endregion #region Helper Methods private static Uri GetUri(FileInfo fileInfo, string reName, string folderName)
{
string http = UriUtil.GetUrl("Operation.ashx");
UriBuilder uriBuilder = new UriBuilder(http);
uriBuilder.Query = string.Format("_fileOper=upload&_fileName={0}&_foldername={1}", reName, folderName);
return uriBuilder.Uri;
} private void PushData(Stream input, Stream output)
{
byte[] buffer = new byte[];
int bytesRead; int totalRead = ; while ((bytesRead = input.Read(buffer, , buffer.Length)) != )
{
output.Write(buffer, , bytesRead);
//Increment the bytes read.
totalRead += bytesRead;
}
} #endregion #region Events and Handlers public delegate void AllFilesUploadCompleted(object sender, FileUploadArgs e);
public event AllFilesUploadCompleted OnAllFilesUploadCompleted; public delegate void FileUploadCompleted(object sender, FileUploadArgs e);
public event FileUploadCompleted OnFileUploadCompleted; public delegate void FileUploadStarted(object sender, FileUploadArgs e);
public event FileUploadStarted OnFileUploadStarted; public delegate void FileUploadError(object sender, FileUploadArgs e);
public event FileUploadError OnFileUploadError; #endregion
}

通过以上代码,方便上传文件至服务器进行操作,例如excel导入。

偕行软件欢迎您光临我们的博客

我们致力于打造国内第一个支持直接在线演示的人力资源管理系统!

我们的官网:http://www.udchn.com

我们的空白开发框架:http://60.211.233.210:8088

我们的集团式人力资源管理系统:http://60.211.233.210:8081

Silverlight 上传文件源代码的更多相关文章

  1. Silverlight从客户端上传文件到服务器

    这里介绍的是一种利用WebClient手动发送Stream到服务器页面的上传文件方法. 一.服务器接收文件 这里使用一个ASHX页面来接收和保存Silverlight传来的Stream,页面代码如下: ...

  2. CKEditor与CKFinder学习--CKFinder源代码改动自己定义上传文件名称

    CKFinder的系列文章到眼下应该说基本能够满足开发需求了,只是另一个小细节,CKFinder默认上传的文件名称和源文件名称一致,假设文件名称反复会自己主动加入编号"(1)"&q ...

  3. 上传文件时 重新载入页面以获取源代码 http://*/upload.php

    今天做一个处理上传文件的接口时碰到这样一个问题, 用的是element-ui的上传组件,但是上传失败, 抓包一看返回的是 重新载入页面以获取源代码 http://*/upload.php 网上搜了一下 ...

  4. HipChat上传文件报未知错误解决方案

    前言 HipChat是Atlassian公司的一款团队协作即时通讯工具,服务端为Linux(官方给的服务端就是一个虚拟机),在Windows.Linux.Android.IOS.Mac等平台都有客户端 ...

  5. PHP上传文件详解 错误提示

    首先在php.ini里配置上载文件.有以下几个重要的配置单: 选项 默认值 说明 post_max_size 8M 控制以后的POST请求的最大规模.必须大于upload_max_filesize选项 ...

  6. AspNet上传文件的几个控件

    本文转载:http://www.cnblogs.com/downmoon/archive/2009/02/05/1384931.html 1.AspnetUpload 地址:http://www.as ...

  7. Flash上传文件(结合asp.net)

    一.实现原理.在某些场合,我们需要使用Flash进行“文件上传”,原因是Flash 能制作出表现力丰富的UI界面. (自负又孤陋寡闻的我在这里做一个补充:Flash使用flash.net包中的File ...

  8. iOS应用内HTTP服务上传文件

    相信很多朋友都用过AirAV.100tv这类iOS视频播放应用中通过Wifi,从PC上输入Web地址上传文件到iOS设备上,我也一直想实现这个功能,苦于知识掌握有限,后来在其他群友的指导下参照很多大神 ...

  9. php 上传文件代码

    通过 PHP,能够把文件上传到server.里面加入一些图片的推断,假设不加推断文件的类型就能够上传随意格式的文件. 为了站点的安全,肯定不让上传php文件,假设有人进入你的后台,上传了一个php文件 ...

随机推荐

  1. @Override报错

    仔细看了下项目 , 是因为有人把project的信息传上来了 , 使用编译的JDK变成了1.5(难道是因为他的1.8的版本我没有 ?) , 右键项目, 选property , 把compiler变成1 ...

  2. 001_JavaScript 错误 - Throw、Try 和 Catch

    try 语句测试代码块的错误. catch 语句处理错误. throw 语句创建自定义错误. 错误一定会发生 当 JavaScript 引擎执行 JavaScript 代码时,会发生各种错误: 可能是 ...

  3. osmdroid启程

    osmdroid一个牛逼的开源地图引擎,从今天开始好好研究一下~

  4. AnyCAD .Net SDK 用户手册 v2013.1

    AnyCAD .Net SDK 用户手册 v2013.1 1. 简介 AnyCAD .Net SDK为.Net4.0开发者提供简单易用的三维建模和三维可视化的API.SDK主要由三维建模的API和可视 ...

  5. 刷了OpenWrt Attitude Adjustment 12.09,很满意

    OpenWrt的这个新版本编译好的固件里集成了luci,图形界面还是很方便的. 装了wpad.qos之后,空间刚好剩下一点点,囧,4M闪存还是不够折腾啊. 发现一个bug:如果空间不够的情况下继续安装 ...

  6. [转]CABasicAnimation用法

    CABasicAnimation用法   CABasicAnimation 自己只有三个property   fromValue  toValue  ByValue 当你创建一个 CABasicAni ...

  7. Flex中使用CSS控制页面样式

    Using file: Stylebounding.mxml Stylebounding2.mxml myCSS0329.css 在Flex4中使用CSS控制样式,既可以直接在MXML文件中写样式,也 ...

  8. 【Linux】netdata监控组件

    github:https://github.com/firehol/netdata 安装:https://github.com/firehol/netdata/wiki/Installation 内存 ...

  9. WinServer2008R2 部署.NET4.0程序 注意事项

    部署注意事项:   1.IIS应用程序池 集成模式   2.在web.config中的system.webServer下,添加 <modules runAllManagedModulesForA ...

  10. NK3C程序配置

    1.坐席软电话 1)NKZXAgent 1)需要环境:.netframework 4.0 2)reg.bat 注册:(确认注册成功) 3)TestAgt.exe 软电话签入测试 LoadConfig: ...