Silverlight 上传文件源代码
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 上传文件源代码的更多相关文章
- Silverlight从客户端上传文件到服务器
这里介绍的是一种利用WebClient手动发送Stream到服务器页面的上传文件方法. 一.服务器接收文件 这里使用一个ASHX页面来接收和保存Silverlight传来的Stream,页面代码如下: ...
- CKEditor与CKFinder学习--CKFinder源代码改动自己定义上传文件名称
CKFinder的系列文章到眼下应该说基本能够满足开发需求了,只是另一个小细节,CKFinder默认上传的文件名称和源文件名称一致,假设文件名称反复会自己主动加入编号"(1)"&q ...
- 上传文件时 重新载入页面以获取源代码 http://*/upload.php
今天做一个处理上传文件的接口时碰到这样一个问题, 用的是element-ui的上传组件,但是上传失败, 抓包一看返回的是 重新载入页面以获取源代码 http://*/upload.php 网上搜了一下 ...
- HipChat上传文件报未知错误解决方案
前言 HipChat是Atlassian公司的一款团队协作即时通讯工具,服务端为Linux(官方给的服务端就是一个虚拟机),在Windows.Linux.Android.IOS.Mac等平台都有客户端 ...
- PHP上传文件详解 错误提示
首先在php.ini里配置上载文件.有以下几个重要的配置单: 选项 默认值 说明 post_max_size 8M 控制以后的POST请求的最大规模.必须大于upload_max_filesize选项 ...
- AspNet上传文件的几个控件
本文转载:http://www.cnblogs.com/downmoon/archive/2009/02/05/1384931.html 1.AspnetUpload 地址:http://www.as ...
- Flash上传文件(结合asp.net)
一.实现原理.在某些场合,我们需要使用Flash进行“文件上传”,原因是Flash 能制作出表现力丰富的UI界面. (自负又孤陋寡闻的我在这里做一个补充:Flash使用flash.net包中的File ...
- iOS应用内HTTP服务上传文件
相信很多朋友都用过AirAV.100tv这类iOS视频播放应用中通过Wifi,从PC上输入Web地址上传文件到iOS设备上,我也一直想实现这个功能,苦于知识掌握有限,后来在其他群友的指导下参照很多大神 ...
- php 上传文件代码
通过 PHP,能够把文件上传到server.里面加入一些图片的推断,假设不加推断文件的类型就能够上传随意格式的文件. 为了站点的安全,肯定不让上传php文件,假设有人进入你的后台,上传了一个php文件 ...
随机推荐
- RabbitMQ介绍6 - 其它
深入话题 Exchange实现路由的方法 http://www.rabbitmq.com/blog/2010/09/14/very-fast-and-scalable-topic-routing-pa ...
- Zigbee组网原理详解
Zigbee组网原理详解 来源:互联网 作者:佚名2015年08月13日 15:57 [导读] 组建一个完整的zigbee网状网络包括两个步骤:网络初始化.节点加入网络.其中节点加入网络又包括两个 ...
- HttpURLConnection 直接发送soap消息调用webservice
httpConn = (HttpURLConnection) new URL(urlString).openConnection(); httpConn.setRequestProperty(& ...
- 快速排序 && 希尔排序 && 插入排序
1. 快速排序 不稳定的排序. 平均(与最好情况)时间复杂度:O(nlgn) | 最坏情况时间复杂度(元素有序,递归栈为 O(n)):O(n2) 适合的数据结构:数组,双向链表. #includ ...
- linux下一对多socket服务器端多线程泄露问题
线程创建多了,没有释放.导致内存泄露... int main() { int len; int on=1; // pMachList = CreateEmptyLinklist(); DataBase ...
- 修复山寨版的J-Link
Fixed J-Link 1. Erase (1) Power On (2) Jump "ERASE"(JP3) (3) Wait for 5s (4) Break ...
- 用于列出选项的Windows窗体控件
可以提供选项列表的控件有ListBox.ComboBox.CheckedListBox,如何正确的使用和选择这些控件,下面对此进行讨论.首先对这三种控件的功能分别进行说明: ListBox ListB ...
- 关于xib文件和storyboard文件的那些事儿
在ios中,一般建议使用代码布局,因为使用代码布局,后期维护容易,拓展容易,并且可以实现动态加载很多数据,但是代码布局比较繁琐,不适合初学者.Xib布局或者Storyboard布局比较方便.下面介绍一 ...
- 解析利用wsdl.exe生成webservice代理类的详解
利用wsdl.exe生成webservice代理类:根据提供的wsdl生成webservice代理类1.开始->程序->Visual Studio 2005 命令提示2.输入如下红色标记部 ...
- 在数学建模中学MATLAB
为期三周的数学建模国赛培训昨天正式结束了,还是有一定的收获的,尤其是在MATLAB的使用上. 1. 一些MATLAB的基础性东西: 元胞数组的使用:http://blog.csdn.net/z1137 ...