非常简单的Silverlight文件上传示例

6
我正在寻找一个在Silverlight中非常简单的文件上传代码片段/解决方案。经过搜索,我发现许多控件/项目都相当复杂,支持多个文件上传、文件上传进度、图像重新采样和大量类。我正在寻找最简单的情况,具有简短、干净且易于理解的代码。
2个回答

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
        }
    } 
}

如果您需要完整的可下载解决方案,请参考我的博客文章:Silverlight中的文件上传 - 简单解决方案


2
为了日后查看此答案的任何人的利益,UploadFileAsync或UploadDataAsync可能更适合这里。OpenWriteAsync非常适合编写流,但它不像fileContent一样接受字节数组作为参数并上传它。OpenWriteCompletedEventHandler意味着“现在可以开始编写流”而不是“上传已完成”。 - Iain Collins
1
谢谢提醒,我之前不知道有UploadFileAsync这个方法。我做了一些搜索发现,在SL2中是不支持的...我会查看它在第3版中是否被支持,并相应地更新代码。 - Gergely Orosz
1
抱歉,Gergley,我匆忙地假设UploadFileAsync会在Silverlight中,因为WebClient是!你是对的,看起来它不是,甚至不在3.0中http://msdn.microsoft.com/en-us/library/system.net.webclient_members.aspx :-( - Iain Collins
你没有提到服务器需要一个Web服务来接收文件 =( =( 像我这样的蠢萌新就会误解! - gideon
我尝试上传了一个文档和一个PPT,但是在上传后,我无法在PowerPoint中打开它,它给出了一个错误提示:“无法打开演示文稿”。看起来数据已经损坏了。还有其他人遇到过同样的错误吗?谢谢。 - Jayesh
代码可能存在错误,因为我大约两年前编写了它。我已经更新了代码以及博客上的代码,那个应该可以工作。 - Gergely Orosz

2

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接