6

I'm looking for a very example file upload code snipplet/solution in Silverlight. Having done search I've found numerous controls/projects but all of them were quite complex; supporting multiple file upload, file upload progress, image re-sampling and lots of classes.

I'm looking for the simplest possible scenario with short, clean and easy to understand code.

JohnC
  • 340
  • 1
  • 2
  • 7

2 Answers2

13

This code is pretty short and (hopefully) easy to understand:

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

For a complete downloadable solution see my blog post on this: File Upload in Silverlight - a Simple Solution

Gergely Orosz
  • 6,475
  • 4
  • 47
  • 59
  • 2
    For the benefit of anyone looking at this answer in future, UploadFileAsync or UploadDataAsync would probably be more appropriate here. OpenWriteAsync is great for writing a stream, but it doesn't take a byte array like fileContent as an argument and upload it. OpenWriteCompletedEventHandler means "The steam is now ready for writing" rather than "The upload is complete". – Iain Collins Dec 10 '09 at 12:36
  • 1
    Thanks for noting, I wasn't aware of UploadFileAsync. I've done a little searching and came across that it wasn't supported in SL2... I'll look into if it's supported in version 3 and update the code accordingly. – Gergely Orosz Dec 10 '09 at 14:49
  • 1
    Oops sorry Gergley I rashly assumed UploadFileAsync would be in Silverlight because WebClient is! You are right, it seems like it is not, not even in 3.0 http://msdn.microsoft.com/en-us/library/system.net.webclient_members.aspx :-( – Iain Collins Dec 11 '09 at 12:27
  • You haven't mentioned one needs a webservice on the the server to receive the file =( =( Dumb noobs like me think otherwise! – gideon Nov 21 '10 at 07:58
  • I tried uploading a doc and a ppt, but after uploading it, I cannot open it in powerpoint, it gives me an error "The presentation cannot be opened." Looks like the data gets corrupted. Did any one else find the same error? Thanks. – Jayesh Aug 21 '11 at 14:34
  • There might have been bugs in the code as I've written it about two years ago. I've updated the code as well as the one on the blog, that one should work. – Gergely Orosz Aug 24 '11 at 14:00
2

Check out this project http://simpleuploader.codeplex.com/. It's allows you to upload multiple files to your server with very-very few lines of code.

Zorayr
  • 23,770
  • 8
  • 136
  • 129