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

5
我正在尝试使用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);
}

但每次我都会遇到这个错误:

远程服务器返回一个错误: (405) 方法不允许。


1
你的服务器代码是什么?它是一个MVC动作吗? - fred
1
你确定你需要使用PUT方法吗?也许你需要发送POST请求? - Emond
需要服务器端代码吗?我认为文件将被上传到服务器中所需的文件夹。如果需要,那么服务器端代码是什么? - MD SHAHIDUL ISLAM
2
错误消息指出给定服务器不允许使用PUT方法。您需要为服务器编写代码,可以创建一个具有控制器和PUT方法的MVC应用程序。 - hazjack
3个回答

16

我使用POST方法和服务器端代码解决了这个问题:

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);
}

服务器端PHP代码 upload.php

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

1
这个错误意味着您正在使用的"PUT"方法被服务器拒绝。请检查响应头中允许的方法。更多信息请参见此处
或者,请查看您尝试上传文件的应用程序文档。

1
错误显示您需要在使用的服务中注册。
对于WCF,您可以像这样进行注册
"%WINDIR%\Microsoft.Net\Framework\v3.0\Windows Communication Foundation\ServiceModelReg.exe" -r HTTP错误405方法不允许

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接