使用 Web 客户端类上传文件


File Uploads with Webclient Class

这是表单的代码:

   form action="upload.php" method="post" enctype="multipart/form-data" 
   input type="file" name="myFile" br
   input type="submit" value="Upload"
   /form

这是服务器端 php 脚本:

if (!empty($_FILES["myFile"])) {
$myFile = $_FILES["myFile"];
if ($myFile["error"] !== UPLOAD_ERR_OK) {
    echo "<p>An error occurred.</p>";
    exit;
}
// ensure a safe filename
$name = preg_replace("/[^A-Z0-9._-]/i", "_", $myFile["name"]);
// don't overwrite an existing file
$i = 0;
$parts = pathinfo($name);
while (file_exists(UPLOAD_DIR . $name)) {
    $i++;
    $name = $parts["filename"] . "-" . $i . "." . $parts["extension"];
}
// preserve file from temporary directory
$success = move_uploaded_file($myFile["tmp_name"],
    UPLOAD_DIR . $name);
if (!$success) { 
    echo "<p>Unable to save file.</p>";
    exit;
}
// set proper permissions on the new file
chmod(UPLOAD_DIR . $name, 0644);
}

从这里偷了剧本http://www.sitepoint.com/file-uploads-with-php/

还有我的 c# 代码上传文件:

private static WebClient _client = new WebClient(); 
private static Uri _address = new Uri("http://tildetictac.x10host.com/upload.php");
_logPath = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + "''log.txt"; //path to the log txt file  
try
    {
        byte[] ret = _client.UploadFile(_address, "POST", _logPath);
    }
    catch (WebException e)
    {
        Console.WriteLine(e.StackTrace);
    }

我不得不屠宰那个html abit才能让它显示。 所以问题是当我尝试上传文件时,webclient 没有显示异常,我已经打印了返回值,什么都没有,它似乎工作正常,除了文件没有添加到目录中。 如果我自己使用表单按钮,单击浏览等,那么它可以正常工作。 权限应该没问题,这一切都是手动工作的,我不明白我怎么会弄乱 webclient 代码,它只有一行长,我已经检查了 url 一百万次,路径是正确的 100%。

在我看来

,您正在使用HTML表单来测试服务器端PHP是否正常工作。

看看你的 html <input type="file" name="myFile"/> .当您 POST 时,数据将保存在 $_FILES 数组中,名称myFile作为键。

当你通过C#的WebClient POST时,它会选择名称应该是什么。尝试修改服务器端 PHP 以检查$_FILES["file"]它应该可以工作。