經過大量的搜索,我發現下面的鏈接:
http://www.paraesthesia.com/archive/2009/12/16/posting-multipartform-data-using-.net-webrequest.aspx
這是C#,所以這裏是一個概念證明我放在一起VB:
Dim boundry As String = "---------------------------" + DateTime.Now.Ticks.ToString("x")
Dim request As WebRequest = WebRequest.Create(Globals.script_path + "uploader.php")
request.Method = "POST"
request.ContentType = "multipart/form-data; boundary=" + boundry
Dim requestStream As Stream = request.GetRequestStream()
'' send text data
Dim data As Hashtable = New Hashtable()
data.Add("text_input", "Hello World")
For Each key As String In data.Keys
Dim item As String = "--" + boundry + vbCrLf + "Content-Disposition: form-data; name=""" & key & """" + vbCrLf + vbCrLf + data.Item(key) + vbCrLf
Dim itemBytes() As Byte = System.Text.Encoding.UTF8.GetBytes(item)
requestStream.Write(itemBytes, 0, itemBytes.Length)
Next
'' send image data
Dim file_header = "--" + boundry + vbCrLf + "Content-Disposition: form-data; name=""file_1"";filename=""file.png""" + vbCrLf + "Content-Type: image/png" + vbCrLf + vbCrLf
Dim file_header_bytes() As Byte = System.Text.Encoding.UTF8.GetBytes(file_header)
requestStream.Write(file_header_bytes, 0, file_header_bytes.Length)
Dim ms As MemoryStream = New MemoryStream()
timecard.screen_shot.Save(ms, ImageFormat.Png)
Dim file_bytes() As Byte = ms.GetBuffer()
ms.Close()
requestStream.Write(file_bytes, 0, file_bytes.Length)
Dim file_footer_bytes() As Byte = System.Text.Encoding.UTF8.GetBytes(vbCrLf)
requestStream.Write(file_footer_bytes, 0, file_footer_bytes.Length)
'' send
Dim endBytes() As Byte = System.Text.Encoding.UTF8.GetBytes("--" + boundry + "--")
requestStream.Write(endBytes, 0, endBytes.Length)
requestStream.Close()
Dim response As WebResponse = request.GetResponse()
Dim reader As StreamReader = New StreamReader(response.GetResponseStream())
Debug.WriteLine(reader.ReadToEnd())
這當然是面向我個人的需求,但我認爲它很好地描述了需要做的事情。對於圖像,有一個文件名。在這種情況下,它不是一個實際的文件。但接收文件的PHP需要這些數據。
這裏是我用來測試這個PHP代碼:
<?php
if (isset($_POST['text_input'])){
echo $_POST['text_input'];
$target_path = "screenshots/";
$target_path = $target_path . basename($_FILES['file_1']['name']);
if(move_uploaded_file($_FILES['file_1']['tmp_name'], $target_path)) {
echo "The file ". basename($_FILES['file_1']['name']).
" has been uploaded";
} else{
echo "There was an error uploading the file, please try again!";
}
}else{
echo "no dta";
}
>
照顧, 李
請不要前綴 「VB NET」 你的標題和這樣的。這就是標籤的用途。 – 2012-03-13 01:53:45
當然,謝謝。 Jonh – 2012-03-13 07:22:31