【发布时间】:2019-09-08 21:36:15
【问题描述】:
我正在尝试从我的 C# 程序通过 POST 请求将文件和一些数据上传到我的服务器,但我总是收到错误 403。
帖子参数是 "id" = 保存文件的文件夹 "pos" = 文件名
因此,如果用户上传文件“abc.text”且 POST 数据为 id="Mario" pos="first",则该文件将保存在 /users/Mario/first.txt 中
我尝试将参数 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