使用 C# 通过 HTTP POST 发送文件 [英] Send a file via HTTP POST with C#

查看:181
本文介绍了使用 C# 通过 HTTP POST 发送文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在搜索和阅读,但没有发现任何真正有用的东西.

I've been searching and reading around to that and couldn't fine anything really useful.

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

I'm writing an small C# win app that allows user to send files to a web server, not by FTP, but by HTTP using POST. Think of it like a web form but running on a windows application.

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

I have my HttpWebRequest object created using something like this

HttpWebRequest req = WebRequest.Create(uri) as HttpWebRequest 

并设置 MethodContentTypeContentLength 属性.但这就是我能走的路.

and also set the Method, ContentType and ContentLength properties. But thats the far I can go.

这是我的一段代码:

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) 
{
}

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

So my question is basically how can I send a fie (text file, image, audio, etc) with C# via HTTP POST.

谢谢!

推荐答案

使用 .NET 4.5(或 .NET 4.0 通过添加 Microsoft.Net.Http 包来自 NuGet)有一种更简单的方法来模拟表单请求.下面是一个例子:

Using .NET 4.5 (or .NET 4.0 by adding the Microsoft.Net.Http package from NuGet) there is an easier way to simulate form requests. Here is an example:

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();
    }
}

这篇关于使用 C# 通过 HTTP POST 发送文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆