简体   繁体   English

使用C#将文件上传到Web服务器

[英]File upload to web server using C#

I am trying to upload file in web server as following using C# 我正在尝试使用C#按照以下方式在Web服务器中上传文件

try
{
    // create WebClient object
    WebClient client = new WebClient();

    string myFile = @"D:\test_file.txt";
    client.Credentials = CredentialCache.DefaultCredentials;

    // client.UploadFile(@"http://mywebserver/myFile", "PUT", myFile);
    client.UploadFile(@"http://localhost/uploads", "PUT", myFile);
    client.Dispose();
}
catch (Exception err)
{
    MessageBox.Show(err.Message);
}

But every time I am getting this error: 但是每次我得到这个错误:

The remote server returned an error: (405) Method Not Allowed. 远程服务器返回错误:(405)不允许使用方法。

I have solved this using the POST method and server side code: 我已经使用POST方法和服务器端代码解决了此问题:

C# code C#代码

try
{
    WebClient client = new WebClient();
    string myFile = @"D:\test_file.txt";
    client.Credentials = CredentialCache.DefaultCredentials;
    client.UploadFile(@"http://localhost/uploads/upload.php", "POST", myFile);
    client.Dispose();
}
catch (Exception err)
{
    MessageBox.Show(err.Message);
}

Server side PHP code upload.php 服务器端PHP代码 upload.php

<?php
    $filepath = $_FILES["file"]["tmp_name"];
    move_uploaded_file($filepath,"test_file.txt");
?>

The error means that the "PUT" method you are using is not allowed by the server. 该错误表示服务器不允许您使用的“ PUT”方法。 Check the response headers for allowed methods. 检查响应标头中允许的方法。 More info here . 更多信息在这里

Or check the documentation for the application to which you are trying to upload the file. 或查看您要向其上载文件的应用程序的文档。

the error is showing that you need to register with the service which you are using 该错误表明您需要注册正在使用的服务

in the case of wcf you can register like this 对于wcf,您可以像这样注册

"%WINDIR%\\Microsoft.Net\\Framework\\v3.0\\Windows Communication Foundation\\ServiceModelReg.exe" -r “%WINDIR%\\ Microsoft.Net \\ Framework \\ v3.0 \\ Windows Communication Foundation \\ ServiceModelReg.exe” -r

HTTP Error 405 Method not allowed HTTP错误405方法不允许

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM