使用C#通过HTTP POST发送文件

gab*_*oju 93 c# post system.net http

我一直在寻找和阅读它,并没有任何真正有用的东西.

我正在编写一个小型C#win应用程序,允许用户将文件发送到Web服务器,而不是通过FTP,而是通过HTTP使用POST.可以把它想象成一个Web表单,但在Windows应用程序上运行.

我使用这样的东西创建了我的HttpWebRequest对象

HttpWebRequest req = WebRequest.Create(uri) as HttpWebRequest 
Run Code Online (Sandbox Code Playgroud)

并且还设置了Method,ContentTypeContentLength属性.但那就是我能走的远.

这是我的一段代码:

HttpWebRequest req = WebRequest.Create(uri) as HttpWebRequest;
req.KeepAlive = false;
req.Method = "POST";
req.Credentials = new NetworkCredential(user.UserName, user.UserPassword);
req.PreAuthenticate = true;
req.ContentType = file.ContentType;
req.ContentLength = file.Length;
HttpWebResponse response = null;

try
{
    response = req.GetResponse() as HttpWebResponse;
}
catch (Exception e) 
{
}
Run Code Online (Sandbox Code Playgroud)

所以我的问题基本上是如何通过HTTP POST用C#发送文件(文本文件,图像,音频等).

谢谢!

Jos*_*des 107

使用.NET 4.5(或通过添加NuGet 的Microsoft.Net.Http包进行.NET 4.0 ),可以更轻松地模拟表单请求.这是一个例子:

private async Task<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 = await client.PostAsync(actionUrl, formData);
        if (!response.IsSuccessStatusCode)
        {
            return null;
        }
        return await response.Content.ReadAsStreamAsync();
    }
}
Run Code Online (Sandbox Code Playgroud)

  • 什么是paramString参数? (9认同)
  • 如果可能,可以显示调用此方法的简单示例? (8认同)
  • 谢谢,非常全面的例子!@eranotzap paramString是要发送的param的**实际值**.`form.Add`的第三个参数是**可选**,仅对文件有用. (2认同)
  • @Ammar,据我所知,我认为您必须将文件读入流或字节 [] 并分别使用 StreamContent 或 ByteArrayContent 。 (2认同)

Mar*_*ell 50

发送原始文件:

using(WebClient client = new WebClient()) {
    client.UploadFile(address, filePath);
}
Run Code Online (Sandbox Code Playgroud)

如果你想用一个模拟一个浏览器表单<input type="file"/>,那就更难了.有关multipart/form-data答案,请参阅答案.


小智 7

对我来说client.UploadFile仍然将内容包装在一个多部分请求中,所以我必须这样做:

using (WebClient client = new WebClient())
{
    client.Headers.Add("Content-Type", "application/octet-stream");
    using (Stream fileStream = File.OpenRead(filePath))
    using (Stream requestStream = client.OpenWrite(new Uri(fileUploadUrl), "POST"))
    {
        fileStream.CopyTo(requestStream);
    }
}
Run Code Online (Sandbox Code Playgroud)


小智 5

我遇到了同样的问题,以下代码完美地解决了这个问题:

//Identificate separator
string boundary = "---------------------------" + DateTime.Now.Ticks.ToString("x");
//Encoding
byte[] boundarybytes = System.Text.Encoding.ASCII.GetBytes("\r\n--" + boundary + "\r\n");

//Creation and specification of the request
HttpWebRequest wr = (HttpWebRequest)WebRequest.Create(url); //sVal is id for the webService
wr.ContentType = "multipart/form-data; boundary=" + boundary;
wr.Method = "POST";
wr.KeepAlive = true;
wr.Credentials = System.Net.CredentialCache.DefaultCredentials;

string sAuthorization = "login:password";//AUTHENTIFICATION BEGIN
byte[] toEncodeAsBytes = System.Text.ASCIIEncoding.ASCII.GetBytes(sAuthorization);
string returnValue = System.Convert.ToBase64String(toEncodeAsBytes);
wr.Headers.Add("Authorization: Basic " + returnValue); //AUTHENTIFICATION END
Stream rs = wr.GetRequestStream();


string formdataTemplate = "Content-Disposition: form-data; name=\"{0}\"\r\n\r\n{1}"; //For the POST's format

//Writting of the file
rs.Write(boundarybytes, 0, boundarybytes.Length);
byte[] formitembytes = System.Text.Encoding.UTF8.GetBytes(Server.MapPath("questions.pdf"));
rs.Write(formitembytes, 0, formitembytes.Length);

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

string headerTemplate = "Content-Disposition: form-data; name=\"{0}\"; filename=\"{1}\"\r\nContent-Type: {2}\r\n\r\n";
string header = string.Format(headerTemplate, "file", "questions.pdf", contentType);
byte[] headerbytes = System.Text.Encoding.UTF8.GetBytes(header);
rs.Write(headerbytes, 0, headerbytes.Length);

FileStream fileStream = new FileStream(Server.MapPath("questions.pdf"), FileMode.Open, FileAccess.Read);
byte[] buffer = new byte[4096];
int bytesRead = 0;
while ((bytesRead = fileStream.Read(buffer, 0, buffer.Length)) != 0)
{
    rs.Write(buffer, 0, bytesRead);
}
fileStream.Close();

byte[] trailer = System.Text.Encoding.ASCII.GetBytes("\r\n--" + boundary + "--\r\n");
rs.Write(trailer, 0, trailer.Length);
rs.Close();
rs = null;

WebResponse wresp = null;
try
{
    //Get the response
    wresp = wr.GetResponse();
    Stream stream2 = wresp.GetResponseStream();
    StreamReader reader2 = new StreamReader(stream2);
    string responseData = reader2.ReadToEnd();
}
catch (Exception ex)
{
    string s = ex.Message;
}
finally
{
    if (wresp != null)
    {
        wresp.Close();
        wresp = null;
    }
    wr = null;
}
Run Code Online (Sandbox Code Playgroud)