c# webrequest post上傳文件與參數

使用c# 向以 API接口發文件,以及文件相關信息。
支持同時發送多個文件。

using System;

using System.Net;
using System.Net.Http;
using System.Collections; 
using System.Collections.Specialized;  
using System.Text;
using System.IO;
using System.Collections.Generic;
using System.Globalization;
// using System.Web.Services.Description;


//https://stackoverflow.com/questions/19954287/how-to-upload-file-to-server-with-http-post-multipart-form-data

namespace test
{
    public class UploadFile
    {
        public UploadFile()
        {
            ContentType = "application/octet-stream";
        }
        public string Name { get; set; }
        public string Filename { get; set; }
        public string ContentType { get; set; }
        public Stream Stream { get; set; }
    

    public byte[] UploadFiles(string address, IEnumerable<UploadFile> files, NameValueCollection values)
    {
        var request = WebRequest.Create(address);
        request.Method = "POST";
        var boundary = "---------------------------" + DateTime.Now.Ticks.ToString("x", NumberFormatInfo.InvariantInfo);
        request.ContentType = "multipart/form-data; boundary=" + boundary;
        boundary = "--" + boundary;

        using (var requestStream = request.GetRequestStream())
        {
            // Write the values
            foreach (string name in values.Keys)
            {
                var buffer = Encoding.ASCII.GetBytes(boundary + Environment.NewLine);
                requestStream.Write(buffer, 0, buffer.Length);
                buffer = Encoding.ASCII.GetBytes(string.Format("Content-Disposition: form-data; name=\"{0}\"{1}{1}", name, Environment.NewLine));
                requestStream.Write(buffer, 0, buffer.Length);
                buffer = Encoding.UTF8.GetBytes(values[name] + Environment.NewLine);
                requestStream.Write(buffer, 0, buffer.Length);
            }

            // Write the files
            foreach (var file in files)
            {
                var buffer = Encoding.ASCII.GetBytes(boundary + Environment.NewLine);
                requestStream.Write(buffer, 0, buffer.Length);

                buffer = Encoding.UTF8.GetBytes(string.Format("Content-Disposition: form-data; name=\"{0}\"; filename=\"{1}\"{2}", file.Name, file.Filename, Environment.NewLine));
                requestStream.Write(buffer, 0, buffer.Length);
                
                buffer = Encoding.ASCII.GetBytes(string.Format("Content-Type: ss{0}{1}{1}", file.ContentType, Environment.NewLine));
                requestStream.Write(buffer, 0, buffer.Length);


                buffer = Encoding.ASCII.GetBytes(string.Format("Content-Type: sss{0}{1}", file.ContentType, Environment.NewLine));
                requestStream.Write(buffer, 0, buffer.Length);

                file.Stream.CopyTo(requestStream);
                buffer = Encoding.ASCII.GetBytes(Environment.NewLine);
                requestStream.Write(buffer, 0, buffer.Length);
            }

            var boundaryBuffer = Encoding.ASCII.GetBytes(boundary + "--");
            requestStream.Write(boundaryBuffer, 0, boundaryBuffer.Length);
        }

        using (var response = request.GetResponse())
        using (var responseStream = response.GetResponseStream())
        using (var stream = new MemoryStream())
        {
            responseStream.CopyTo(stream);
            return stream.ToArray();
        }
    }
    }

    class Program
    {

        static   void Main(string[] args)
        {

            string url = "http;//example.com/uploadimg";
            string dumpPath = "F:/content/test/Capture2.PNG";
            var stream = File.Open(dumpPath, FileMode.Open);
            var files = new[] 
            {
                new UploadFile
                {
                    Name = "file",
                    Filename = Path.GetFileName(dumpPath),
                    ContentType = "text/plain",
                    Stream = stream
                }
            };

            var values = new NameValueCollection
            {
                { "client", "VIP" },
                { "fileFullPath", "John Doe" },
            };
           UploadFile uf = new UploadFile();
            byte[] result = uf.UploadFiles(url, files, values);

        }
    }
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章