c#

c# curl文件上传怎么实现

小樊
136
2024-07-10 01:00:29
栏目: 编程语言

在C#中实现文件上传可以通过使用HttpWebRequest类来发送HTTP POST请求,并在请求中包含要上传的文件。以下是一个示例代码,演示如何使用C#实现文件上传:

using System;
using System.IO;
using System.Net;

class Program
{
    static void Main(string[] args)
    {
        string url = "http://example.com/upload";
        string filePath = "path/to/file.txt";

        HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
        request.Method = "POST";

        string boundary = "---------------------------" + DateTime.Now.Ticks.ToString("x");
        request.ContentType = "multipart/form-data; boundary=" + boundary;

        using (Stream requestStream = request.GetRequestStream())
        {
            using (StreamWriter writer = new StreamWriter(requestStream))
            {
                writer.WriteLine("--" + boundary);
                writer.WriteLine("Content-Disposition: form-data; name=\"file\"; filename=\"" + Path.GetFileName(filePath) + "\"");
                writer.WriteLine("Content-Type: application/octet-stream");
                writer.WriteLine();

                using (FileStream fileStream = new FileStream(filePath, FileMode.Open, FileAccess.Read))
                {
                    byte[] buffer = new byte[4096];
                    int bytesRead;
                    while ((bytesRead = fileStream.Read(buffer, 0, buffer.Length)) != 0)
                    {
                        requestStream.Write(buffer, 0, bytesRead);
                    }
                }

                writer.WriteLine();
                writer.WriteLine("--" + boundary + "--");
            }
        }

        using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
        {
            using (Stream responseStream = response.GetResponseStream())
            {
                using (StreamReader reader = new StreamReader(responseStream))
                {
                    string responseText = reader.ReadToEnd();
                    Console.WriteLine(responseText);
                }
            }
        }
    }
}

在上述代码中,首先创建一个HttpWebRequest对象,并设置请求的方法为POST。然后设置请求的Content-Type为multipart/form-data,并定义一个boundary用于分隔请求的不同部分。接着将文件内容写入请求的流中,并在结束时添加boundary标记。最后发送请求并读取响应内容。

请注意,以上示例中使用了HttpWebRequest类来实现文件上传,也可以考虑使用更方便的第三方库,如HttpClient来实现文件上传。

0
看了该问题的人还看了