我正在Silverlight中寻找一个非常示例的文件上传代码snipplet /解决方案。完成搜索后,我发现了许多控制/项目,但所有这些都非常复杂;支持多文件上传,文件上传进度,图像重新采样和许多类。
我正在寻找最简单的方案,包括简短,干净且易于理解的代码。
答案 0 :(得分:13)
这段代码很简短(希望)易于理解:
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
答案 1 :(得分:2)
查看此项目http://simpleuploader.codeplex.com/。它允许您使用非常少的代码行将多个文件上传到您的服务器。
答案 2 :(得分:0)
请参阅这篇文章。本文介绍如何使用非常简单的UI上传单个文件并对每个步骤进行说明。 http://aspilham.blogspot.com/2010/04/file-upload-in-chunks-using-silverlight.html