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(" --" + boundary + " ");
            byte[] endBoundaryBytes = Encoding.UTF8.GetBytes(" --" + boundary + "-- ");

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

            //请求头部信息
            StringBuilder sbHeader = new StringBuilder(string.Format("Content-Disposition:form-data;name="file";filename="{0}" Content-Type:application/octet-stream ", 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步骤了

原文地址:https://www.cnblogs.com/myloveblogs/p/5050796.html