我正在寻找一个很好的示例文件上传代码snipplet /解决方案在Silverlight中。完成搜索后,我发现了很多控件/项目,但所有这些都很复杂;支持多文件上传,文件上传进度,图像重采样和大量课程。非常简单的Silverlight文件上传示例
我正在寻找简单,干净和易于理解的代码的最简单的可能情况。
我正在寻找一个很好的示例文件上传代码snipplet /解决方案在Silverlight中。完成搜索后,我发现了很多控件/项目,但所有这些都很复杂;支持多文件上传,文件上传进度,图像重采样和大量课程。非常简单的Silverlight文件上传示例
我正在寻找简单,干净和易于理解的代码的最简单的可能情况。
此代码是很短,(希望)很容易理解:
public const int CHUNK_SIZE = 4096;
public const string UPLOAD_URI = "http://localhost:55087/FileUpload.ashx?filename={0}&append={1}";
private Stream _data;
private string _fileName;
private long
_bytesTotal;
private long _bytesUploaded;
private void UploadFileChunk()
{
string uploadUri = ""; // Format the upload URI according to wether the it's the first chunk of the file
if (_bytesUploaded == 0)
{
uploadUri = String.Format(UPLOAD_URI,_fileName,0); // Dont't append
}
else if (_bytesUploaded < _bytesTotal)
{
uploadUri = String.Format(UPLOAD_URI, _fileName, 1); // append
}
else
{
return; // Upload finished
}
byte[] fileContent = new byte[CHUNK_SIZE];
_data.Read(fileContent, 0, CHUNK_SIZE);
WebClient wc = new WebClient();
wc.OpenWriteCompleted += new OpenWriteCompletedEventHandler(wc_OpenWriteCompleted);
Uri u = new Uri(uploadUri);
wc.OpenWriteAsync(u, null, fileContent);
_bytesUploaded += fileContent.Length;
}
void wc_OpenWriteCompleted(object sender, OpenWriteCompletedEventArgs e)
{
if (e.Error == null)
{
object[] objArr = e.UserState as object[];
byte[] fileContent = objArr[0] as byte[];
int bytesRead = Convert.ToInt32(objArr[1]);
Stream outputStream = e.Result;
outputStream.Write(fileContent, 0, bytesRead);
outputStream.Close();
if (_bytesUploaded < _bytesTotal)
{
UploadFileChunk();
}
else
{
// Upload complete
}
}
}
对于一个完整的解决方案下载上看到这个我的博客文章:File Upload in Silverlight - a Simple Solution
退房这个项目http://simpleuploader.codeplex.com/。它允许你用很少的代码行将多个文件上传到你的服务器。
请参阅这篇文章。本文展示了如何使用非常简单的用户界面和每个步骤的解释来上传单个文件。 http://aspilham.blogspot.com/2010/04/file-upload-in-chunks-using-silverlight.html
感谢您的链接! – JohnC 2009-10-27 21:42:47
为了以后有人看到这个答案的好处,UploadFileAsync或UploadDataAsync在这里可能会更合适。 OpenWriteAsync非常适合编写一个流,但它不需要像fileContent这样的字节数组作为参数并上传它。 OpenWriteCompletedEventHandler意味着“蒸汽已准备好写入”而不是“上传完成”。 – 2009-12-10 12:36:40
感谢您的注意,我并不知道UploadFileAsync。我已经做了一些搜索,发现它在SL2中不受支持......我会研究它是否在版本3中受支持并相应地更新代码。 – 2009-12-10 14:49:34