1. 程式人生 > >C#Post檔案上傳

C#Post檔案上傳

上程式碼:

public static string Upload(string url, string fileName)
{
    HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
    request.Method = "POST";
    Stream postStream = new MemoryStream();
    #region 處理Form表單檔案上傳
    //通過表單上傳檔案
    string boundary = "----" + DateTime.Now.Ticks.ToString("x");
    string formdataTemplate = "\r\n--" + boundary + "\r\nContent-Disposition: form-data; name=\"{0}\"; filename=\"{1}\"\r\nContent-Type: application/octet-stream\r\n\r\n";


    try
    {
        //準備檔案流
        using (var fileStream = FileToStream(fileName))
        {
            var formdata = string.Format(formdataTemplate, "", System.IO.Path.GetFileName(fileName) /*Path.GetFileName(fileName)*/);
            var formdataBytes = Encoding.UTF8.GetBytes(postStream.Length == 0 ? formdata.Substring(2, formdata.Length - 2) : formdata);//第一行不需要換行
            postStream.Write(formdataBytes, 0, formdataBytes.Length);

            //寫入檔案
            byte[] buffer = new byte[1024];
            int bytesRead = 0;
            while ((bytesRead = fileStream.Read(buffer, 0, buffer.Length)) != 0)
            {
                postStream.Write(buffer, 0, bytesRead);
            }
        }
    }
    catch (Exception ex)
    {
        throw ex;
    }

    //結尾
    var footer = Encoding.UTF8.GetBytes("\r\n--" + boundary + "--\r\n");
    postStream.Write(footer, 0, footer.Length);
    request.ContentType = string.Format("multipart/form-data; boundary={0}", boundary);

    #endregion

    request.ContentLength = postStream != null ? postStream.Length : 0;
    request.Accept = "*/*";
    //request.Accept = "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8";
    request.KeepAlive = true;
    request.UserAgent = "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/31.0.1650.57 Safari/537.36";

    #region 輸入二進位制流
    if (postStream != null)
    {
        postStream.Position = 0;

        //直接寫入流
        Stream requestStream = request.GetRequestStream();

        byte[] buffer = new byte[1024];
        int bytesRead = 0;
        while ((bytesRead = postStream.Read(buffer, 0, buffer.Length)) != 0)
        {
            requestStream.Write(buffer, 0, bytesRead);
        }

        postStream.Close();//關閉檔案訪問
    }
    #endregion

    HttpWebResponse response = (HttpWebResponse)request.GetResponse();

    using (Stream responseStream = response.GetResponseStream())
    {
        using (StreamReader myStreamReader = new StreamReader(responseStream,Encoding.GetEncoding("utf-8")))
        {
            string retString = myStreamReader.ReadToEnd();
            return retString;
        }
    }
}

FileToStream方法,檔案轉stream

public static Stream FileToStream(string fileName)

{
    // 開啟檔案

    FileStream fileStream = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.Read);

    // 讀取檔案的 byte[]

    byte[] bytes = new byte[fileStream.Length];

    fileStream.Read(bytes, 0, bytes.Length);

    fileStream.Close();

    // 把 byte[] 轉換成 Stream

    Stream stream = new MemoryStream(bytes);

    return stream;

}