CSharp - 在 C# 中,使用 HTTP POST 发送文件

  显示原文与译文双语对照的内容

如果用户可以发送文本文件,而不使用流读取器,则可以使用 C# 。xml 。excel 。csv等方式发送文件。

时间: 原作者:

你可以尝试以下代码:


 public void PostMultipleFiles(string url, string[] files)


{


 string boundary ="----------------------------" + DateTime.Now.Ticks.ToString("x");


 HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create(url);


 httpWebRequest.ContentType ="multipart/form-data; boundary=" + boundary;


 httpWebRequest.Method ="POST";


 httpWebRequest.KeepAlive = true;


 httpWebRequest.Credentials = System.Net.CredentialCache.DefaultCredentials;


 Stream memStream = new System.IO.MemoryStream();


 byte[] boundarybytes =System.Text.Encoding.ASCII.GetBytes("rn--" + boundary +"rn");


 string formdataTemplate ="rn--" + boundary +"rnContent-Disposition: form-data; name="{0}";rnrn{1}";


 string headerTemplate ="Content-Disposition: form-data; name="{0}"; filename="{1}"rn Content-Type: application/octet-streamrnrn";


 memStream.Write(boundarybytes, 0, boundarybytes.Length);


 for (int i = 0; i <files.Length; i++)


 {


 string header = string.Format(headerTemplate,"file" + i, files[i]);


//string header = string.Format(headerTemplate,"uplTheFile", files[i]);


 byte[] headerbytes = System.Text.Encoding.UTF8.GetBytes(header);


 memStream.Write(headerbytes, 0, headerbytes.Length);


 FileStream fileStream = new FileStream(files[i], FileMode.Open,


 FileAccess.Read);


 byte[] buffer = new byte[1024];


 int bytesRead = 0;


 while ((bytesRead = fileStream.Read(buffer, 0, buffer.Length))!= 0)


 {


 memStream.Write(buffer, 0, bytesRead);


 }


 memStream.Write(boundarybytes, 0, boundarybytes.Length);


 fileStream.Close();


 }


 httpWebRequest.ContentLength = memStream.Length;


 Stream requestStream = httpWebRequest.GetRequestStream();


 memStream.Position = 0;


 byte[] tempBuffer = new byte[memStream.Length];


 memStream.Read(tempBuffer, 0, tempBuffer.Length);


 memStream.Close();


 requestStream.Write(tempBuffer, 0, tempBuffer.Length);


 requestStream.Close();


 try


 {


 WebResponse webResponse = httpWebRequest.GetResponse();


 Stream stream = webResponse.GetResponseStream();


 StreamReader reader = new StreamReader(stream);


 string var = reader.ReadToEnd();



 }


 catch (Exception ex)


 {


 response.InnerHtml = ex.Message;


 }


 httpWebRequest = null;


}



原作者:

使用. NET 4.5 ( 或者. NET 4.0通过从NuGet添加 Microsoft.Net.Http 软件包) 可以更轻松地模拟表单请求。 以下是一个示例:


private System.IO.Stream Upload(string actionUrl, string paramString, Stream paramFileStream, byte [] paramFileBytes)


{


 HttpContent stringContent = new StringContent(paramString);


 HttpContent fileStreamContent = new StreamContent(paramFileStream);


 HttpContent bytesContent = new ByteArrayContent(paramFileBytes);


 using (var client = new HttpClient())


 using (var formData = new MultipartFormDataContent())


 {


 formData.Add(stringContent,"param1","param1");


 formData.Add(fileStreamContent,"file1","file1");


 formData.Add(bytesContent,"file2","file2");


 var response = client.PostAsync(actionUrl, formData).Result;


 if (!response.IsSuccessStatusCode)


 {


 return null;


 }


 return response.Content.ReadAsStreamAsync().Result;


 }


}



试试这个


string fileToUpload = @"c:usertest.txt";


string url ="http://example.com/upload";


using (var client = new WebClient())


{


byte[] result = client.UploadFile(url, fileToUpload);


string responseAsString = Encoding.Default.GetString(result);


}



...