【问题标题】:C# How do I upload a file to a PHP server?C# 如何将文件上传到 PHP 服务器?
【发布时间】:2010-12-03 16:11:58
【问题描述】:

我需要从 C# 程序将文件上传到我的网络服务器。问题是,我还需要同时发布两个字符串。 到目前为止,我有:

            HttpWebRequest HttpWReq = (HttpWebRequest)WebRequest.Create("http://localhost/test.php");             
            ASCIIEncoding encoding = new ASCIIEncoding();
            string postData = "&name=Test";
            postData += "&email=a@a.com";
            postData += "&file=file.txt";

            byte[] data = encoding.GetBytes(postData);

            HttpWReq.Method = "POST";    
            HttpWReq.ContentType = "application/x-www-form-urlencoded";   
            HttpWReq.ContentLength = data.Length;    
            Stream newStream = HttpWReq.GetRequestStream();


            newStream.Write(data, 0, data.Length);
            newStream.Close();

这是 HTML 和 PHP:

<?php
$name = $_POST['name'];
$email = $_POST['email'];
$target_path = "uploads/";
$target_path = $target_path . basename( $_FILES['uploadedfile']['name']);
echo (move_uploaded_file($_FILES['uploadedfile']['tmp_name'], $target_path) ? "Success!" : "Failed");
?>
<form enctype="multipart/form-data" action="test.php" method="POST">
Name : <input type="text" name="name"><br />
Email : <input type="text" name="email"><br />
File : <input name="uploadedfile" type="file" /><br />
<input type="submit" value="Being Upload" />
</form>

我不知道在哪里添加文件字段:\ 任何帮助将不胜感激!

【问题讨论】:

标签: c# php file upload field


【解决方案1】:

请注意,您在 PHP 文件中的 HTML sn-p 正确地在 &lt;form&gt; 元素中有 enctype="multipart/form-data",当您的表单提交包含文件上传时,它必须使用 multipart/form-data 内容类型或其他多部分 MIME 类型,但在您的 C# 代码中,您将 HTTP 请求 ContentType 设置为 application/x-www-form-urlencoded。该内容类型不支持文件提交。上传的文件必须是表单提交所在的 MIME 消息中的单独部分。

我无法提供代码示例,因为我一般不精通 C# 或 .NET,但我相信应该有一个类来构造此类消息,它可能与电子邮件处理相关.

【讨论】:

    【解决方案2】:

    也许可以尝试添加FileUpload Class from MSDN,或者在您的项目中使用 CURL。

    【讨论】:

    • 好吧,无论如何,我不知道如何以相同的形式上传它们。例如,如果我使用 FileUpload 方法,它会上传文件,然后提交其余的表单......我想同时完成所有这些......哈,我不确定这是否有意义:\
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-07-02
    • 1970-01-01
    • 2017-06-02
    • 1970-01-01
    • 2017-04-25
    • 2019-11-18
    • 2021-02-03
    相关资源
    最近更新 更多