使用Webclient类进行文件上载

时间:2016-02-18 23:35:39

标签: c# php file-upload

这是表格的代码:

   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代码,它只是一行很长,我已经检查了一百万次网址,路径是正确的100%。

1 个答案:

答案 0 :(得分:1)

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

看一下你的html <input type="file" name="myFile"/>。 POST时,数据将保存在名为$_FILES的{​​{1}}数组中作为密钥。

当您通过C#的myFile发帖时,它会选择名称应该是什么。尝试修改服务器端PHP以检查WebClient,它应该可以工作。