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. ADF_Starting系列7_使用EJB/JPA/JSF通过ADF构建Web应用程序之创建UI View

    2013-05-01 Created By BaoXinjian

  2. 理解Python装饰器

    装饰器本质上是一个Python函数,它可以让其他函数在不需要做任何代码变动的前提下增加额外功能,装饰器的返回值也是一个函数对象.它经常用于有切面需求的场景,比如:插入日志.性能测试.事务处理.缓存.权 ...

  3. ubuntu下设置clion是使用clang和clang++

    链接 http://stackoverflow.com/questions/31725681/how-to-setup-clion-with-portable-clang-on-ubuntu I go ...

  4. [SharpZipLib 未能加载文件或程序集] 解决方法

    未能加载文件或程序集"ICSharpCode.SharpZipLib, Version=0.86.0.518, Culture=neutral, PublicKeyToken=1b03e6a ...

  5. 【摘】top命令

    1.重要参数解释 VIRT:virtual memory usage.Virtual这个词很神,一般解释是:virtual adj.虚的, 实质的, [物]有效的, 事实上的.到底是虚的还是实的?让G ...

  6. spring定时器设置(转自:http://my.oschina.net/LvSantorini/blog/520049)

    转自:http://my.oschina.net/LvSantorini/blog/520049<!-- MessageRequestTask类中包含了msgRequest方法,用于执行定时任务 ...

  7. 博客后台迁移至i.cnblogs.com及小经验分享

    大家好!我们已经将博客后台从原来的 www.cnblogs.com/博客地址名/admin/ 迁移至独立的二级域名 i.cnblogs.com.如果您发现任何问题,麻烦您立即向我们反馈. 虽然这次迁移 ...

  8. HDOJ2222 Keywords Search-AC自动机

    Problem Description In the modern time, Search engine came into the life of everybody like Google, B ...

  9. Android IOS WebRTC 音视频开发总结(七二)-- 看到Google Duo,你想到了什么?

    本文主要介绍在线教育这个行业,文章最早发表在我们的微信公众号上,支持原创,详见这里, 欢迎关注微信公众号blackerteam,更多详见www.rtc.help 在昨天的Google I/O大会上Go ...

  10. 使用get传参的时候,参数在后头获取不到或者出现别的错误。

    把传递的参数使用encode转换一下,符合HTTP规定的编码,再使用. String encode = java.net.URLEncoder.encode("VSrYJoDat8z7Ad9 ...