考虑以下HTML代码
<form action="upload.php" method="post" enctype="multipart/form-data">
<input type="file" name="file">
</form>
现在我需要使用c#来实现它。 我把文件放在一个字节数组中。
byte[] data;
String fileName;
那我该怎么做呢我想我必须创建一个合适的HTTP POST请求。但是怎么样? 我尝试使用HttpWebRequest类。但不知道如何继续。
HttpWebRequest oRequest = null;
oRequest = (HttpWebRequest)HttpWebRequest.Create("http://localhost/cs.php");
oRequest.ContentType = "multipart/form-data";
oRequest.Method = "POST";
注意:文件'upload.php'与HTML代码完美配合。
答案 0 :(得分:1)
将文件上传控制作为runat服务器并尝试使用代码
int contentLength = fileUpload.PostedFile.ContentLength;
byte[] data = new byte[contentLength];
fileUpload.PostedFile.InputStream.Read(data, 0, contentLength);
// Prepare web request...
HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create("http://localhost/cs.php");
webRequest.Method = "POST";
webRequest.ContentType = "multipart/form-data";
webRequest.ContentLength = data.Length;
using (Stream postStream = webRequest.GetRequestStream())
{
// Send the data.
postStream.Write(data, 0, data.Length);
postStream.Close();
}
<强>更新强>
// Create a request using a URL that can receive a post.
WebRequest request = WebRequest.Create ("http://localhost/cs.php ");
// Set the Method property of the request to POST.
request.Method = "POST";
// Create POST data and convert it to a byte array.
byte[] byteArray = data;
// Set the ContentType property of the WebRequest.
request.ContentType = "application/x-www-form-urlencoded";
// Set the ContentLength property of the WebRequest.
request.ContentLength = byteArray.Length;
// Get the request stream.
Stream dataStream = request.GetRequestStream ();
// Write the data to the request stream.
dataStream.Write (byteArray, 0, byteArray.Length);
// Close the Stream object.
dataStream.Close ();
// Get the response.
WebResponse response = request.GetResponse ();
// Display the status.
Console.WriteLine (((HttpWebResponse)response).StatusDescription);
// Get the stream containing content returned by the server.
dataStream = response.GetResponseStream ();
// Open the stream using a StreamReader for easy access.
StreamReader reader = new StreamReader (dataStream);
// Read the content.
string responseFromServer = reader.ReadToEnd ();
// Display the content.
Console.WriteLine (responseFromServer);
// Clean up the streams.
reader.Close ();
dataStream.Close ();
response.Close ();
答案 1 :(得分:1)
您可以使用System.Net.WebClient
:
using(WebClient client = new WebClient()) {
client.UploadFile(address, filePath);
}