c# .net core upload files in multipart/form-data format

 (1) Upload files

The method adopted is: manually splicing the body content of the http request

using System;
using System.Collections.Specialized;
using System.IO;
using System.Net;
using System.Net.Security;
using System.Security.Cryptography.X509Certificates;
using System.Text;
using System.Linq;



/// <summary>
/// multipart/form-data上传文件
/// </summary>
/// <param name="url">请求的url地址</param>
/// <param name="stringDict">post参数</param>
/// <param name="fileName">文件名</param>
/// <param name="file">文件</param>
/// <param name="fileKeyName">文件这一项参数的key</param>
/// <param name="timeOut">超时间隔_秒</param>
/// <returns>失败返回null</returns>
public static string HttpPostData(string url, NameValueCollection stringDict,
                    string fileName, MemoryStream file, string fileKeyName = "file", int timeOut = 20)
{

    System.GC.Collect();//垃圾回收,回收没有正常关闭的http连接

    timeOut = timeOut * 1000;
    string responseContent;

    MemoryStream memStream = null;
    Stream requestStream = null;
    HttpWebResponse httpWebResponse = null;
    HttpWebRequest webRequest = null;

    try
    {
        memStream = new MemoryStream();
        webRequest = (HttpWebRequest)WebRequest.Create(url);
        // 边界符  
        var boundary = "---------------" + DateTime.Now.Ticks.ToString("x");
        // 边界符  
        var beginBoundary = Encoding.ASCII.GetBytes("--" + boundary + "\r\n");
        // 最后的结束符  
        var endBoundary = Encoding.ASCII.GetBytes("--" + boundary + "--\r\n");

        // 设置属性  
        webRequest.Method = "POST";
        webRequest.Timeout = timeOut;
        webRequest.ContentType = "multipart/form-data; boundary=" + boundary;

        // 写入字符串的Key  
        var stringKeyHeader = "--" + boundary +
                                "\r\nContent-Disposition: form-data; name=\"{0}\"" +
                                "\r\n\r\n{1}\r\n";

        foreach (byte[] formitembytes in from string key in stringDict.Keys
                                            select string.Format(stringKeyHeader, key, stringDict[key])
                                                into formitem
                                            select Encoding.UTF8.GetBytes(formitem))
        {
            memStream.Write(formitembytes, 0, formitembytes.Length);
        }

        // 写入文件  
        const string filePartHeader =
            "Content-Disposition: form-data; name=\"{0}\"; filename=\"{1}\"\r\n" +
                "Content-Type: application/octet-stream\r\n\r\n";
        var header = string.Format(filePartHeader, fileKeyName, fileName);
        var headerbytes = Encoding.UTF8.GetBytes(header);

        memStream.Write(beginBoundary, 0, beginBoundary.Length);
        memStream.Write(headerbytes, 0, headerbytes.Length);

        var buffer = new byte[1024];
        int bytesRead; // =0  
        file.Seek(0, SeekOrigin.Begin);
        while ((bytesRead = file.Read(buffer, 0, buffer.Length)) != 0)
        {
            memStream.Write(buffer, 0, bytesRead);
        }

        // 写入换行  
        var contentLine = Encoding.ASCII.GetBytes("\r\n");
        memStream.Write(contentLine, 0, contentLine.Length);

        // 写入最后的结束边界符  
        memStream.Write(endBoundary, 0, endBoundary.Length);

        webRequest.ContentLength = memStream.Length;

        requestStream = webRequest.GetRequestStream();

        memStream.Position = 0;
        var tempBuffer = new byte[memStream.Length];
        memStream.Read(tempBuffer, 0, tempBuffer.Length);
        //memStream.Close();

        requestStream.Write(tempBuffer, 0, tempBuffer.Length);
        //requestStream.Close();

        httpWebResponse = (HttpWebResponse)webRequest.GetResponse();

        using (var httpStreamReader = new StreamReader(httpWebResponse.GetResponseStream(),
                                                        Encoding.GetEncoding("utf-8")))
        {
            responseContent = httpStreamReader.ReadToEnd();
        }
    }
    finally
    {
        if (memStream != null) { memStream.Close(); }
        if (requestStream != null) { requestStream.Close(); }
        if (httpWebResponse != null) { httpWebResponse.Close(); }
        if (webRequest != null) { webRequest.Abort(); }
    }

    return responseContent;
}

 

 

(2) Download files

Receive the file stream returned by the url and return byte data

using System;
using System.IO;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Web.Http;


namespace FileTest.Controllers
{
    [Route("api/[controller]/[action]")]
    public class A1Controller : ApiController
    {

        [HttpGet]
        public HttpResponseMessage test()
        {
            byte[] bytes = download("http://xxx.com/yyy.jpg");

            try
            {
                var stream = new MemoryStream(bytes);
                HttpResponseMessage response = new HttpResponseMessage(HttpStatusCode.OK);
                response.Content = new StreamContent(stream);
                response.Content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
                response.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment")
                {
                    FileName = "a1.jpg"
                };
                return response;
            }
            catch
            {
                return new HttpResponseMessage(HttpStatusCode.NoContent);
            }
        }


        /// <summary>
        /// 下载文件,返回byte数组
        /// </summary>
        /// <returns></returns>
        public static byte[] download(string url)
        {
            byte[] bytes = null;

            HttpWebRequest request = null;
            HttpWebResponse response = null;

            //请求url以获取数据
            try
            {
                //设置最大连接数
                ServicePointManager.DefaultConnectionLimit = 200;

                /***************************************************************
                * 下面设置HttpWebRequest的相关属性
                * ************************************************************/
                request = (HttpWebRequest)WebRequest.Create(url);
                //request.UserAgent = USER_AGENT;
                request.Method = "GET";

                //获取服务器返回
                response = (HttpWebResponse)request.GetResponse();

                //只改了返回数据的接收
                //获取HTTP返回数据
                Stream stream = response.GetResponseStream();
                int count = (int)response.ContentLength;
                int offset = 0;
                bytes = new byte[count];
                
                // 写循环是因为听说,直接读取偶尔会读不全
                while (count > 0)
                {
                    int n = stream.Read(bytes, offset, count);
                    if (n == 0) break;
                    count -= n;
                    offset += n;
                }
                stream.Close();
                return bytes;
            }
            catch (System.Threading.ThreadAbortException e)
            {
                System.Threading.Thread.ResetAbort();
            }
            catch (WebException e)
            {
                if (e.Status == WebExceptionStatus.ProtocolError)
                {
                }
                throw new Exception(e.ToString());
            }
            catch (Exception e)
            {
                throw new Exception(e.ToString());
            }
            finally
            {
                //关闭连接和流
                if (response != null)
                {
                    response.Close();
                }
                if (request != null)
                {
                    request.Abort();
                }
            }

            return null;

        }


    }
}

 

Guess you like

Origin blog.csdn.net/u013595395/article/details/112719228