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. 【转】C#环形队列

    概述 看了一个数据结构的教程,是用C++写的,可自己C#还是一个菜鸟,更别说C++了,但还是大胆尝试用C#将其中的环形队列的实现写出来,先上代码: 1 public class MyQueue< ...

  2. 配置ActiveX控件在网页中下载安装

    先检查客户端浏览器是否安装了ActiveX控件,如果没有安装ActiveX,就需要先给浏览器提示下载并允许安装.否则就直接使用该ActiveX控件.我们可以使用CodeBase来满足我们的要求:下面是 ...

  3. Mono addin 学习笔记 2

    下面分析用xml描述文件的方式来进行插件定义 定义扩展点如下: public interface ISnippetProvider { string GetText (string shortcut) ...

  4. MSSQL导入导出数据

    /******* 导出到excel */ EXEC master..xp_cmdshell 'bcp SettleDB.dbo.shanghu out c:\temp1.xls -c -q -S&qu ...

  5. EXT学习之——EXT下拉框默认绑定第一个值

    //默认第一个下拉框绑定值if (this.moduleCombo.store.getAt(0) != undefined) { this.moduleCombo.setValue(this.modu ...

  6. express 4 中 session的处理(仅为博主笔记)

    1.app.js var express = require('express') var app = express();var routers = require('./router/index' ...

  7. 纸上谈兵:堆(heap)

    作者:Vamei 出处:http://www.cnblogs.com/vamei 欢迎转载,也请保留这段声明.谢谢! 堆(heap)又被为优先队列(priority queue).尽管名为优先队列,但 ...

  8. 【转载】大数据量传输时配置WCF的注意事项

    WCF传输数据量的能力受到许多因素的制约,如果程序中出现因需要传输的数据量较大而导致调用WCF服务失败的问题,应注意以下配置: 1.MaxReceivedMessageSize:获取或设置配置了此绑定 ...

  9. C# 分部类与分部方法

    一.定义 分部方法是指能够使编码人员跨多个代码文件实现类型的语法.简而言之.它可以让我们在一个文件中构建方法原型,而在另一个文件中实现 使用分部方法和分部类需要使用关键词partial,且紧靠在cla ...

  10. LR工具使用之结果分析

    LR工具使用之结果分析 1.启动loadrunner第三个控件Analysis分析测试结果.