Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Very simple Silverlight File Upload example [closed]

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.

like image 979
JohnC Avatar asked Oct 25 '09 23:10

JohnC


2 Answers

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

like image 76
Gergely Orosz Avatar answered Oct 24 '22 05:10

Gergely Orosz


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.

like image 2
Zorayr Avatar answered Oct 24 '22 05:10

Zorayr