C# NET 微信臨時素材上傳


最近在做這個,一開始也是不明白為什么給個URL帶着兩個參數就直接上傳了,網上看了很多都是PHP,但是PHP沒看過是不會 的

所以就一直在找網上什么Demo之類的講解,最后還是不錯找到了一個比較好理解的例子。

整個過程是這樣的:

1、我們首先建一個項目

2、項目建好后就一個簡單的file控件和一個submit提交按鈕我們這里要用表單提交

上代碼:

 

 

<html>
<head>
    <title>qweqw</title>
</head>
<body>
    @using (Html.BeginForm("Upload", "Source", FormMethod.Post, new { enctype = "multipart/form-data" }))
    {
        <text>選擇上傳文件:</text><input name="file" type="file" id="file" />
        <br />
        <br />
        <input type="submit" name="Upload" value="Upload" />
    }

</body>
</html>

3、前台完了那就到后台了對吧

 

看代碼:

 


        [HttpPost]
        public ActionResult Upload(FormCollection form)
        {
         
            if (Request.Files.Count == 0)
            {
                //Request.Files.Count 文件數為0上傳不成功
                return View();
            }

            var file = Request.Files[0];
            if (file.ContentLength == 0)
            {
                //文件大小大(以字節為單位)為0時,做一些操作
                return View();
            }
            else
            {
                //文件大小不為0
                HttpPostedFileBase files = Request.Files[0];
                //保存成自己的文件全路徑,newfile就是你上傳后保存的文件,
                string newFile = DateTime.Now.ToString("yyyyMMddHHmmss") ;
                Access_token model = new Access_token();
                model = pub.Check_Token();
                string type = "image";
                string url = string.Format("http://file.api.weixin.qq.com/cgi-bin/media/upload?access_token={0}&type={1}", model.access_token, type.ToString());
                string path = "D://項目//個人//Senparc.Weixin.MP.Sample//Senparc.Weixin.MP.Sample//image//" + files.FileName;
                //服務器上的UpLoadFile文件夾必須有讀寫權限      
                files.SaveAs(path);
                string filename = System.Web.HttpContext.Current.Server.MapPath("/image/" + files.FileName);
                string json = HttpUploadFile(url, filename);
                JObject jb = (JObject)JsonConvert.DeserializeObject(json);//這里就能知道返回正確的消息了下面是個人的邏輯我就沒寫

       ..........................................

            }          
            
            return Content("成功");

        }
        public static string HttpUploadFile(string url, string path)//這個方法是兩個URL第一個url是條到微信的,第二個是本地圖片路徑
        {
            // 設置參數
            HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;
            CookieContainer cookieContainer = new CookieContainer();
            request.CookieContainer = cookieContainer;
            request.AllowAutoRedirect = true;
            request.Method = "POST";
            string boundary = DateTime.Now.Ticks.ToString("X"); // 隨機分隔線
            request.ContentType = "multipart/form-data;charset=utf-8;boundary=" + boundary;
            byte[] itemBoundaryBytes = Encoding.UTF8.GetBytes("\r\n--" + boundary + "\r\n");
            byte[] endBoundaryBytes = Encoding.UTF8.GetBytes("\r\n--" + boundary + "--\r\n");

            int pos = path.LastIndexOf("\\");
            string fileName = path.Substring(pos + 1);

            //請求頭部信息
            StringBuilder sbHeader = new StringBuilder(string.Format("Content-Disposition:form-data;name=\"file\";filename=\"{0}\"\r\nContent-Type:application/octet-stream\r\n\r\n", fileName));
            byte[] postHeaderBytes = Encoding.UTF8.GetBytes(sbHeader.ToString());

            FileStream fs = new FileStream(path, FileMode.Open, FileAccess.Read);
            byte[] bArr = new byte[fs.Length];
            fs.Read(bArr, 0, bArr.Length);
            fs.Close();

            Stream postStream = request.GetRequestStream();
            postStream.Write(itemBoundaryBytes, 0, itemBoundaryBytes.Length);
            postStream.Write(postHeaderBytes, 0, postHeaderBytes.Length);
            postStream.Write(bArr, 0, bArr.Length);
            postStream.Write(endBoundaryBytes, 0, endBoundaryBytes.Length);
            postStream.Close();

            //發送請求並獲取相應回應數據
            HttpWebResponse response = request.GetResponse() as HttpWebResponse;
            //直到request.GetResponse()程序才開始向目標網頁發送Post請求
            Stream instream = response.GetResponseStream();
            StreamReader sr = new StreamReader(instream, Encoding.UTF8);
            //返回結果網頁(html)代碼
            string content = sr.ReadToEnd();
            return content;
        }

4、前台的這句話@using (Html.BeginForm("Upload", "Source", FormMethod.Post, new { enctype = "multipart/form-data" }))中

new { enctype = "multipart/form-data" }是必須要的,

這樣就會訪問到Upload這個方法接下來就兩個方法的執行了那么就看第3步驟了


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM