Question File transfer via port 80

KofY

New member
Joined
Oct 26, 2021
Messages
1
Programming Experience
Beginner
Hello
I want to implement file transfer in a bunch of C # and PHP.
Client-side function:
Client:
public void Upload()
        {
            string uriString = "http://127.0.0.1/upload.php";
            WebClient myWebClient = new WebClient();
            myWebClient.Headers.Add("Content-Type", "text/plain");
            myWebClient.UploadFile(uriString, "POST", @"С:\test.txt");
        }
And this is how the server-side receive function is implemented.
Server:
$upload_dir = "/var/html/www/uploads/";
$upload_file = $upload_dir . $_FILES['file']['name'];
$tmp_name = $_FILES['file']['tmp_name'];
move_uploaded_file($tmp_name, $upload_file);
The problem is that there are no errors in the transfer ($ _FILES ['file'] ['error'] returns 0), but I still can't see the file on the server.
The uploads folder with permissions 777, $ _FILES ['file'] ['name'] inside stores the correct file name, file transfer in PHP is enabled.
if (move_uploaded_file ()) fails altogether.
1. What is the error of receiving the file?
2. If I want to convey something other than text - how to implement it? The option is that if we transfer a text file, then we send the argument "text / plain" to the function; use a different MIME-type for the picture, but this is somehow bad from the point of view of the code.
 
You can see the WebClient reference source to to see .NET Framework uploads a file:

From that you can infer the answer for #2: You need to set the web client's headers to use a different mime type, but it looks like it wants the type to start with "multipart/":

As for #1. I don't know enough of the guts of how PHP works, but from the .NET side, you can check the return value of UploadFile() to see if the client side got an error back from the server.

Based on the PHP documentation, it looks like you need to do more to get the appropriate temporary name:

 
Last edited:
If you follow to source of OpenFileInternal you'll also see the file name is in "filename" and not "name".
Scratch that, PHP translates this to its own [file] array of fields.
 
Last edited:
Do you actually need to set a custom Content-Type for the form data? It seems WebClient always set it to application/octet-stream for file uploads.
Important

We don't recommend that you use the WebClient class for new development. Instead, use the System.Net.Http.HttpClient class.
Here is an example with that:
C#:
using (var data = new MultipartFormDataContent())
using (var c = new ByteArrayContent(File.ReadAllBytes(file)))
{
    c.Headers.ContentType = new MediaTypeHeaderValue(MimeMapping.GetMimeMapping(file));
    data.Add(c, "file", Path.GetFileName(file));
    client.PostAsync(url, data);
}
MimeMapping is from System.Web assembly, you may have your own way to determine Mime type.
 

Latest posts

Back
Top Bottom