Call WeChat JS to upload photos and js to upload photos.

Source: Internet
Author: User

Call the JS photo upload API to upload images and js to upload photos.

Public ActionResult UploadImge (string serverId) {var headPath = "/UploadImage/" + DateTime. now. toString ("yyyyMM"); string AbsoluteFilePath = Server. mapPath (headPath); if (! Directory. exists (AbsoluteFilePath) {Directory. createDirectory (AbsoluteFilePath);} string imgPath = headPath + "/" + DateTime. now. toString ("yyyyMMddHHmm") + serverId + ". jpg "; // source image string AbsolutePath = Server. mapPath (imgPath); WeChatClient. saveMultimedia (serverId, AbsolutePath); return Json (imgPath);} public ActionResult UploadImge2 (string serverId) {var headPath = "/UploadImage/" + DateTime. no W. ToString ("yyyyMM"); string AbsoluteFilePath = Server. MapPath (headPath); if (! Directory. exists (AbsoluteFilePath) {Directory. createDirectory (AbsoluteFilePath);} string imgPath = headPath + "/" + DateTime. now. toString ("yyyyMMddHHmm") + serverId + ". jpg "; string AbsolutePath = Server. mapPath (imgPath); WeChatClient. saveMultimedia (serverId, AbsolutePath); CommonUtil. makeThumbnail (AbsolutePath, AbsolutePath. replace (". jpg "," _2.jpg "), 3, 4); // crop return Json (imgPath) in a ratio of 3 to 4;} publ Ic ActionResult UploadImge3 (string serverId) {var headPath = "/UploadImage/" + DateTime. now. toString ("yyyyMM"); string AbsoluteFilePath = Server. mapPath (headPath); if (! Directory. exists (AbsoluteFilePath) {Directory. createDirectory (AbsoluteFilePath);} string imgPath = headPath + "/" + DateTime. now. toString ("yyyyMMddHHmm") + serverId + ". jpg "; string AbsolutePath = Server. mapPath (imgPath); WeChatClient. saveMultimedia (serverId, AbsolutePath); CommonUtil. makeThumbnail (AbsolutePath, AbsolutePath. replace (". jpg "," _3.jpg "), 4, 3); // crop the image at a ratio of 4 to 3. return Json (imgPath );}
Public static void MakeThumbnail (string originalImagePath, string thumbnailPath, int bw = 4, int bh = 3) {try {Image originalImage = Image. fromFile (originalImagePath); var bl = originalImage. height * 1.00/originalImage. width; int orgWith, orgHeight, startY = 0, startX = 0, newWith, newHeight = 0; var bd = bh * 1.00/bw; if (bl> bd) {orgWith = originalImage. width; orgHeight = (int) (originalImage. width * bh/bw); startY = (originalImage. height-orgHeight)/2; newWith = orgWith; if (newWith> 720) {newWith = 720;} newHeight = (int) (newWith * bh/bw );} else {orgWith = originalImage. height * bw/bh; orgHeight = originalImage. height; startX = (originalImage. width-orgWith)/2; newWith = orgWith; if (newWith> 720) {newWith = 720;} newHeight = (int) (newWith * bh/bw );} bitmap destBitmap = new Bitmap (newWith, newHeight); // target MAP Rectangle destRect = new Rectangle (0, 0, newWith, newHeight ); // rectangular container Rectangle srcRect = new Rectangle (startX, startY, orgWith, orgHeight); var g = Graphics. fromImage (destBitmap); // set the high quality interpolation method g. interpolationMode = System. drawing. drawing2D. interpolationMode. high; // set High quality, low speed rendering smoothness g. smoothingMode = System. drawing. drawing2D. smoothingMode. highQuality; // clear the canvas and fill g with a transparent background color. clear (Color. transparent); try {g. drawImage (originalImage, destRect, srcRect, GraphicsUnit. pixel); destBitmap. save (thumbnailPath, originalImage. rawFormat);} catch (System. exception e) {} finally {originalImage. dispose (); destBitmap. dispose (); g. dispose () ;}} catch (Exception ){}}}
public static void SaveMultimedia(string MEDIA_ID, string savepath)        {            string file = string.Empty;            string strpath = string.Empty;            string stUrl = "http://file.api.weixin.qq.com/cgi-bin/media/get?access_token=" + MyToken.Token + "&media_id=" + MEDIA_ID;            HttpWebRequest req = (HttpWebRequest)HttpWebRequest.Create(stUrl);            req.Method = "GET";            using (WebResponse wr = req.GetResponse())            {                HttpWebResponse myResponse = (HttpWebResponse)req.GetResponse();                strpath = myResponse.ResponseUri.ToString();                WebClient mywebclient = new WebClient();                try                {                    mywebclient.DownloadFile(strpath, savepath);                }                catch (Exception ex)                {                    savepath = ex.ToString();                }            }        }
Var uploadNum = 0; wx. config ({debug: false, // enable the debugging mode. The returned values of all called APIs are displayed in the client alert. To view the input parameters, you can open them on the pc, the parameter information is output through log and printed only on the pc end. AppId: '*********', // required. The only identifier of the public number is timestamp: '@ (ViewBag. timestamp) ', // required. The signature generation timestamp nonceStr:' @ (ViewBag. nonceStr) ', // required. The random string signature:' @ (ViewBag. signature) ', // required, and signature. For details, see Appendix 1 jsApiList: ['selectesimage', 'previewimag', 'uploadimag', 'downloadimage'] // required, list of JS interfaces to be used. For the list of all JS interfaces, see Appendix 2}); function uploadImge () {var ttnum = 5-uploadNum; wx. chooseImage ({count: ttnum, // default 9 sizeType: ['compressed '], // you can specify the source image or a compressed image. Both have sourceType: ['album' by default ', 'camera '], // you can specify whether the source is an album or a camera. By default, both have success: function (res) {var localIds = res. localIds; // return the local ID list of the selected image. localId can be used as the src attribute of the img label to display the image uploadImg (localIds, 0) ;}};} function uploadImg (localIds, num) {if (localIds. length <= num) {return;} var localId = localIds [num]; wx. uploadImage ({localId: localId, // local ID of the image to be uploaded, isShowProgressTips: 1 is obtained by the chooseImage interface, // The default value is 1, and the Progress prompt success: function (sres) is displayed) {var serverId = sres. serverId; // The server ID of the returned image $. post ("/WeiXin/Home/UploadImge3", {serverId: serverId}, function (data) {var picPath = $ ("# PicPath "). val (); if (picPath = "") {picPath = data;} else {picPath = picPath + "," + data ;}$ ("# PicPath "). val (picPath); var temphtml = ""; if (window. _ wxjs_is_wkwebview) {wx. getLocalImgData ({localId: localId, // localID success: function (res) {var localData = res. localData; // localData is the base64 data of the image, you can use the img label to display temphtml = '<div class = "col-xs-6"> ;$ ("# picdiv "). before (temphtml); uploadNum = uploadNum + 1; if (uploadNum> = 5) {$ ("# picdiv "). hide () ;}uploadimg (localIds, num + 1 )}});} else {temphtml = '<div class = "col-xs-6"> ;$ ("# picdiv "). before (temphtml); uploadNum = uploadNum + 1; if (uploadNum> = 5) {$ ("# picdiv "). hide () ;}uploadimg (localIds, num + 1 )}})}});}

 

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.