您的位置:首页 > 编程语言

Silverlight 上传文件源代码

2013-08-29 20:31 113 查看
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 = 0;

//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[4096];
int bytesRead;

int totalRead = 0;

while ((bytesRead = input.Read(buffer, 0, buffer.Length)) != 0)
{
output.Write(buffer, 0, 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
}


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

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

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

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

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

我们的集团式人力资源管理系统:http://60.211.233.210:8081
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: