使用C#发送文件和数据错误403. CURL没有错误

问题描述 投票:0回答:1

我正在尝试使用来自我的C#程序的POST请求上传文件和一些数据到我的服务器,但我总是收到错误403。

post params是“id”=文件夹,其中文件将被保存“pos”=文件的名称

因此,如果用户上传文件“abc.text”和POST数据为id =“Mario”pos =“first”,该文件将保存在/users/Mario/first.txt中

我试图改变params id和pos作为GET,但我总是有错误403

C#响应

{StatusCode: 403, ReasonPhrase: 'Forbidden', Version: 1.1, 
Content: System.Net.Http.StreamContent, 
Headers:{  Vary: Accept-Encoding  X-Varnish: 818481486  Age: 0  
X-Cache: MISS  Transfer-Encoding: chunked  Connection: keep-alive  
Date: Thu, 18 Apr 2019 14:29:10 GMT  Content-Type: text/html; 
charset=iso-8859-1}}

我的代码:

<!DOCTYPE html>
<html>
<head>
  <title>Upload your files</title>
</head>
<body>
  <form enctype="multipart/form-data" action="uploader2.php" method="POST">
    <p>Upload your file</p>
    <input type="file" name="uploaded_file"></input><br />
    <input type="input" name="id"></input><br />
    <input type="input" name="pos"></input><br />
    <input type="submit" value="Upload"></input>
  </form>
</body>
</html>
<!-- language: lang-php -->
<?PHP
  if(!empty($_FILES['uploaded_file']))
  {
    $path = "users/".$_POST['id']."/";

    if(!is_dir($path))  
        {  
        if(!mkdir ($path,0777,true))
            echo 'Error creating folder!';  
        }  

    $path = $path.$_POST['pos'].".txt";

    if(move_uploaded_file($_FILES['uploaded_file']['tmp_name'], $path)) {
      echo "Ok";
    } else{
        echo "Failed!";
    }
  }
?>

这是我的C#代码

using (var httpClient = new HttpClient())
{   
    MultipartFormDataContent multipartContent = new MultipartFormDataContent();
    var fp = File.ReadAllBytes("file.txt");

    multipartContent.Add(new StringContent("Mario"), "id");
    multipartContent.Add(new StringContent("first"), "pos");
    multipartContent.Add(new ByteArrayContent(fp, 0, fp.Length), "uploaded_file", "file.txt");
    HttpResponseMessage response = await httpClient.PostAsync("http://host.com/uploader2.php", multipartContent);

    response.EnsureSuccessStatusCode();
    httpClient.Dispose();
    string sd = response.Content.ReadAsStringAsync().Result;
    }
}
c# php post upload http-status-code-403
1个回答
0
投票

https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS

在你的php脚本中使用它:

header("Access-Control-Allow-Origin: *"); // wildcard allows access to all domains

Access-Control-Allow-Origin是CORS(跨源资源共享)头。

当站点A尝试从站点B获取内容时,站点B可以发送一个Access-Control-Allow-Origin响应头来告诉浏览器该页面的内容可以访问某些来源。 (原点是域,加上方案和端口号。)默认情况下,站点B的页面不能被任何其他来源访问;使用Access-Control-Allow-Origin标头为特定请求源的跨域访问打开了一扇门。

© www.soinside.com 2019 - 2024. All rights reserved.