Posts Tagged ‘UploadFile’
18
Nov

Simple File Upload Solution

Post a comment » Popularity: 4%

Gergely Orosz target to implement a simple solution in uploading file using Silverlight. The upload control contains a progress indicator where you can keep track of the upload progress. The sample also showed you how you can collect the uploaded file using PHP or C#.

Simple File Upload Solution

25
Sep

Upload file using File Dialog

Post a comment » Popularity: 1%

The coding below demonstrating how you might utilize your FileDialog to upload files from your local disk to server.

The code demonstrated the following:

  1. Limited the selection of JPG and PNG files only
  2. Only 1 file can be selected
  3. Upload the file with the corresponding file name
  4. How to get the file data inside PHP

Upload file using File Dialog 

Select and upload file in c#:
OpenFileDialog dialog = new OpenFileDialog();
dialog.Filter = "Image Files (.jpg,.png)|*.JPG;*.jpg;*.PNG;*.png";
dialog.FilterIndex = 1;
bool? userClickedOK = _imageDialog.ShowDialog();

// Process input if the user clicked OK.
if (userClickedOK == true)
{
    UploadFile(dialog.File.Name, dialog.File.OpenRead());
}

private void UploadFile(string filename, Stream data)
{
    UriBuilder ub = new UriBuilder(UPLOAD_PATH);
    ub.Query = string.Format("filename={0}", filename);

    WebClient c = new WebClient();
    c.OpenWriteCompleted += (sender, e) =>
    {
        PushData(data, e.Result);
        e.Result.Close();
        data.Close();
    };
    c.OpenWriteAsync(ub.Uri, "Post");
}

private void PushData(Stream input, Stream output)
{
    byte[] buffer = new byte[4096];
    int bytesRead;

    while ((bytesRead = input.Read(buffer, 0, buffer.Length)) != 0)
    {
        output.Write(buffer, 0, bytesRead);
    }
}
Get and save file in PHP:
$filepath = $_REQUEST['filename'];
$handle = fopen("php://input", "r");
$file = fopen($filepath,"w");

if($file != null && $handle != null)
{
        while ($data = fread($handle, 8192)) fwrite($file, $data);
        fclose($handle);
        fclose($file);
}