25
Sep

Upload file using File Dialog

2 Comments » 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);
}
  • DZone
  • Digg
  • del.icio.us
  • StumbleUpon
  • Reddit

Related Posts

2 Responses to “Upload file using File Dialog”

  1. Brilliant highlights pertaining to upload files for getting myself get moving. I most certainly will keep this specific website link and get back to this.

  2. Lottie Lein says:

    Thanks for this informative post. I look forward more of your writing on this topic sometime soon. Thanks again

Leave a Reply