C#通过HttpWebRequest上传文件(自测通过)

C#通过HttpWebRequest进行文件上传,自己亲测没问题,如果需要请自取

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Reflection;
using System.Text;

namespace ConsoleApp1
{
    internal class Program
    {
        static void Main(string[] args)
        {
            var url = "http://www.afosoallwx.cn/zhTestApi/public/admin.php/wechat/Afscdouniontransaction/Afsupload";
            var path = "C:\\Users\\Administrator\\Pictures\\Saved Pictures\\景甜.jpg";
            FileUploader.UploadFile(url, path);

            Console.WriteLine("success");
            Console.ReadLine();
        }
    }

    public class FileUploader
    {
        public static void UploadFile(string url, string filePath, string fieldName = "file")
        {
            var fileInfo = new FileInfo(filePath);

            var request = (HttpWebRequest)WebRequest.Create(url);

            request.Method = "POST";

            // 设置ContentType为multipart/form-data,并包含一个随机生成的boundary  
            var boundary = "----------------------------" + DateTime.Now.Ticks.ToString("x");
            request.ContentType = "multipart/form-data; boundary=" + boundary;

            // 这里简化了处理过程,通常你需要更详细地构建POST数据  
            // 包括文件和其他表单字段  

            // 假设你已经有了构建好的POST数据(bytes),以下是如何写入这些数据  
            using (var requestStream = request.GetRequestStream())
            {
                // 这里应该写入完整的multipart/form-data请求体  
                // 但为了简化,我们仅模拟写入一些数据  
                var buffer = Encoding.UTF8.GetBytes("--" + boundary + "\r\n");
                var header = $"Content-Disposition: form-data; name=\"{fieldName}\"; filename=\"{fileInfo.Name}\"\r\nContent-Type: {GetMimeType(fileInfo.Extension)}\r\n\r\n";
                var headerBytes = Encoding.UTF8.GetBytes(header);

                // 假设fileBytes是文件的字节数组  
                byte[] fileBytes = File.ReadAllBytes(filePath);

                // 写入boundary、header和文件内容  
                requestStream.Write(buffer, 0, buffer.Length);
                requestStream.Write(headerBytes, 0, headerBytes.Length);
                requestStream.Write(fileBytes, 0, fileBytes.Length);

                // 写入结尾boundary  
                var footer = Encoding.UTF8.GetBytes("\r\n--" + boundary + "--\r\n");
                requestStream.Write(footer, 0, footer.Length);
            }

            // 发送请求并接收响应  
            using (var response = (HttpWebResponse)request.GetResponse())
            {
                // 处理响应...  
                using (var resStream = response.GetResponseStream())
                {
                    using (StreamReader myStreamReader = new StreamReader(resStream, Encoding.UTF8))
                    {
                        string retString = myStreamReader.ReadToEnd();
                        Console.WriteLine(retString);
                    }
                }
            }

        }

        // 根据文件扩展名返回MIME类型,这里需要扩展以支持更多类型  
        private static string GetMimeType(string extension)
        {
            switch (extension.ToLower())
            {
                case ".jpg":
                case ".jpeg":
                    return "image/jpeg";
                case ".png":
                    return "image/png";
                // 添加更多case来处理其他文件类型  
                default:
                    return "application/octet-stream";
            }
        }
    }

}

 

posted @ 2024-07-01 22:32  段江涛IT  阅读(113)  评论(0编辑  收藏  举报
页脚HTML代码