温馨提示×

C# form-data如何处理大文件

c#
小樊
106
2024-07-16 16:42:55
栏目: 编程语言

处理大文件时,可以使用C#中的流式处理来避免将整个文件加载到内存中。以下是一个示例代码,演示如何处理大文件的form-data:

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

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

        HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
        request.Method = "POST";
        request.ContentType = "multipart/form-data; boundary=---------------------------12345";

        using (var requestStream = request.GetRequestStream())
        {
            using (var fileStream = File.OpenRead(filePath))
            {
                byte[] boundaryBytes = Encoding.ASCII.GetBytes("-----------------------------12345\r\n");
                byte[] headerBytes = Encoding.ASCII.GetBytes($"Content-Disposition: form-data; name=\"file\"; filename=\"{Path.GetFileName(filePath)}\"\r\nContent-Type: application/octet-stream\r\n\r\n");
                byte[] footerBytes = Encoding.ASCII.GetBytes("\r\n-----------------------------12345--\r\n");

                requestStream.Write(boundaryBytes, 0, boundaryBytes.Length);
                requestStream.Write(headerBytes, 0, headerBytes.Length);

                byte[] buffer = new byte[4096];
                int bytesRead;
                while ((bytesRead = fileStream.Read(buffer, 0, buffer.Length)) > 0)
                {
                    requestStream.Write(buffer, 0, bytesRead);
                }

                requestStream.Write(footerBytes, 0, footerBytes.Length);
            }
        }

        try
        {
            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            using (Stream receiveStream = response.GetResponseStream())
            {
                StreamReader readStream = new StreamReader(receiveStream, Encoding.UTF8);
                Console.WriteLine(readStream.ReadToEnd());
            }
        }
        catch (WebException ex)
        {
            Console.WriteLine("Error uploading file: " + ex.Message);
        }
    }
}

上面的代码中,我们使用File.OpenRead()方法打开要上传的大文件,并使用流式处理的方式逐块将文件内容写入HttpWebRequest的请求流中。这样可以避免将整个文件加载到内存中,从而有效处理大文件的form-data。

0