Uploading images with c # windows forms and php

1

I've been trying to find a solution to my problem for at least two weeks and I can not seem to make it work. The idea is this: I have an application Windows Forms written in C# , in which I will have a OpenFileDialog that will select the path to a .png image or .jpg on the client computer , and selected this path, when I click save, the image needs to be renamed ( can be for date of day ), sent to a service in PHP as in the example below:

<?php

    if(isset($_FILES['fileUpload']))
    {
        //Pegando extensão do arquivo
        $ext = strtolower(substr($_FILES['fileUpload']['name'],-4)); 

        $name = $_FILES['fileUpload']['name'];

        $dir = './upload/'; //Diretório para uploads 

        //Fazer upload do arquivo
        move_uploaded_file($_FILES['fileUpload']['tmp_name'], $dir.$name); 
        echo("Imagen enviada com sucesso!");
    }  

Basically the idea is to upload images using C# ( from a client application Windows Forms ) and send it to PHP () or direct to the destination directory on the server ).

The problem here is basically:

  

Catch the image -> rename of the image -> send to uploads folder on the server.

Note: The image must be renamed before being sent to the server, since I associate the static name of the image with a record in the database to fetch the image later. / p>     

asked by anonymous 02.02.2017 / 00:01

1 answer

1

Use the System.Net.Http.HttpClient , sending a post to the address of script php , and System.Net.Http.MultipartFormDataContent to send the photo or any file to the server. In the name configuration I put the generation through Guid for no name repetition.

if (openFileDialog1.ShowDialog() == DialogResult.OK)
{
    string fileName = openFileDialog1.FileName;

    System.Net.Http.StreamContent streamContent = new System.Net.Http.StreamContent(
        System.IO.File.Open(fileName, System.IO.FileMode.Open)
    );

    System.Net.Http.MultipartFormDataContent form = 
        new System.Net.Http.MultipartFormDataContent();

    form.Add(streamContent, "fileUpload", string.Format("{0}{1}",
                               Guid.NewGuid(),
                               System.IO.Path.GetExtension(fileName)));

    System.Net.Http.HttpClient http = new System.Net.Http.HttpClient();             
    http.BaseAddress = new Uri("http://localhost");
    var res = http.PostAsync("send.php", form)
        .Result.Content;

    string r = res.ReadAsStringAsync().Result;

    http.Dispose();
}

This code is a basis, is functional and can be changed through your business rules.

> php I did not make any changes.

References:

02.02.2017 / 01:02