Upload images with c# windows Forms and php

Asked

Viewed 440 times

1

I’ve been trying to find a solution to my problem for at least two weeks and I can’t make it work. The idea is, I have an application Windows Forms written in C#, in which I will have a OpenFileDialog which will select the path to an image .png or .jpg in the customer’s computer, and selected this path, when I click record, the image needs to be renamed (may be for date of day), and then sent to a service at 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 an application Windows Forms) on the customer’s side and send this to the PHP (or directly to the destination directory on the server).

The problem here is basically:

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

Observing: the image has to be renamed before it is sent to the server, since I associate the static name of the image with a record in the database to later fetch the image.

1 answer

1


Use the System.Net.Http.Httpclient, sending a post to the address of script , and System.Net.Http.Multipartformdatacontent to send the photo or any file to the server. In the name setting I put the generation by Guid for there to be no repetition of the name.

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 its business rules.

Observing: In the script I made no change.

References:

  • 1

    Perfect! Thank you! You helped me out more with this, thank you very much!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.