public string UpLoadToAliOss(string url, string ext, string sourceUlr, string title) { string aliTempImgKey = string.Empty; if (!url.Contains("http")) { return(aliTempImgKey = $"{WebSiteConfig.cdnurl}content/default_qrcode.png"); //"http://j.vzan.cc/dz/content/default_qrcode.png"; } byte[] data = null; try { using (WebClient web = new WebClient()) { data = web.DownloadData(url); } var aliTempImgFolder = AliOSSHelper.GetOssImgKey(ext, false, out aliTempImgKey); var putResult = AliOSSHelper.PutObjectFromByteArray(aliTempImgFolder, data, 1, "." + ext); if (!putResult) { log4net.LogHelper.WriteInfo(typeof(AliOSSHelper), "下载图片上传失败!图片同步到Ali失败!"); //上传失败 return(string.Empty); } } catch (Exception ex) { log4net.LogHelper.WriteInfo(typeof(AliOSSHelper), ex.Message + "---" + url + "---" + sourceUlr + "---" + title); return(string.Empty); } return(aliTempImgKey); }
/// <summary> /// 将另外的图片路径上传到我们服务器,返回我们服务器的图片路径 /// </summary> /// <param name="url"></param> /// <param name="isreload">是否获取了新路径</param> /// <returns></returns> public static string GetMyServerImgUrl(string url, ref bool isreload) { if (string.IsNullOrEmpty(url)) { return(""); } if (url.Contains("i.vzan.cc")) { return(url); } string aliTempImgKey = ""; using (WebClient web = new WebClient()) { byte[] data = web.DownloadData(url); string aliTempImgFolder = AliOSSHelper.GetOssImgKey("jpg", false, out aliTempImgKey); if (AliOSSHelper.PutObjectFromByteArray(aliTempImgFolder, data, 1, ".jpg")) { isreload = true; return(aliTempImgKey); } } return(""); }
public ReturnMsg Upload(string utoken, string filetype = "img") { // 检查是否是 multipart/form-data if (!Request.Content.IsMimeMultipartContent()) { result.msg = "不支持的上传类型"; return(result); } HttpFileCollection files = HttpContext.Current.Request.Files; if (files.Count <= 0) { result.msg = "请选择要上传的文件"; return(result); } using (Stream stream = files[0].InputStream) { string fileExtension = Path.GetExtension(files[0].FileName).ToLower(); HashSet <string> img = new HashSet <string>() { ".jpg", ".jpeg", ".png", ".gif", ".bmp" }; HashSet <string> video = new HashSet <string>() { ".mp4", ".rmvb", ".flv" }; if (filetype == "img" && !img.Contains(fileExtension)) { result.msg = $"上传失败!只支持:{string.Join(",", img)}格式的图片!"; return(result); } else if (filetype == "video" && !video.Contains(fileExtension)) { result.msg = $"上传失败!只支持:{string.Join(",", img)}格式的视频!"; return(result); } byte[] imgByteArray = new byte[stream.Length]; stream.Read(imgByteArray, 0, imgByteArray.Length); // 设置当前流的位置为流的开始 stream.Seek(0, SeekOrigin.Begin); //开始上传 string url = string.Empty; string ossurl = AliOSSHelper.GetOssImgKey(fileExtension.Replace(".", ""), false, out url); bool putResult = AliOSSHelper.PutObjectFromByteArray(ossurl, imgByteArray, 1, fileExtension); if (putResult) { result.code = 1; result.msg = "上传成功"; result.obj = url; } else { result.msg = "上传失败"; result.obj = ""; } return(result); } }
public string SaveImageToAliOSS(byte[] byteArray) { string aliTempImgKey = string.Empty; string aliTempImgFolder = AliOSSHelper.GetOssImgKey("jpg", false, out aliTempImgKey); AliOSSHelper.PutObjectFromByteArray(aliTempImgFolder, byteArray, 1, ".jpg"); return(aliTempImgKey); }
private void UploadImage() { //var FileCollect = Request.Files[UploadConfig.UploadFieldName]; HttpFileCollection FileCollect = System.Web.HttpContext.Current.Request.Files; string uploadFileName = ""; int imgWidth, imgHeigth; string ext = string.Empty; if (FileCollect.Count > 0) { uploadFileName = FileCollect[domname].FileName; var size = FileCollect[domname].ContentLength; var fileStream = FileCollect[domname].InputStream; var byteData = new byte[size]; if (null != fileStream) { using (System.IO.BinaryReader br = new System.IO.BinaryReader(fileStream)) { byteData = br.ReadBytes(size); } }// 上传的文件为空 else { } if (uploadFileName.Contains(".")) { ext = uploadFileName.Split('.')[uploadFileName.Split('.').Length - 1]; } else { Utility.ImgHelper.IsImgageType(byteData, "jpg", out ext); } //不是图片格式不让上传 string[] ImgType = new string[] { "jpg", "jpeg", "gif", "png", "bmp" }; string[] VodType = new string[] { "mp4", "avi", "rmvb", "avi", "rm" }; if (ImgType.Contains <string>(ext.ToLower())) { Result.Url = uploadimg(byteData, out imgWidth, out imgHeigth, size, ext); } else if (VodType.Contains <string>(ext.ToLower())) { try { string aliTempImgKey = string.Empty; var aliTempImgFolder = AliOSSHelper.GetOssVoiceKey(ext.ToLower(), true, "video/folder", out aliTempImgKey); var putResult = AliOSSHelper.PutObjectFromByteArray(aliTempImgFolder, byteData, 1, "." + ext.ToLower()); Result.Url = aliTempImgKey; } catch (Exception ex) { log4net.LogHelper.WriteInfo(this.GetType(), ex.Message); } } } Result.OriginFileName = uploadFileName; Result.State = UploadState.Success; WriteResult(); }
public ActionResult SaveImgByServerId(string media_id = "") { int times = 1; reGetToken: string token = WxHelper.GetToken(webview_appid, webview_appsecret, false); string url = string.Empty; var posturl = string.Format("http://file.api.weixin.qq.com/cgi-bin/media/get?access_token={0}&media_id={1}", token, media_id); HttpWebRequest req = (HttpWebRequest)HttpWebRequest.Create(posturl); byte[] result = null; using (WebResponse response = req.GetResponse()) { //在这里对接收到的页面内容进行处理 Stream stream = response.GetResponseStream(); List <byte> bytes = new List <byte>(); int temp = stream.ReadByte(); while (temp != -1) { bytes.Add((byte)temp); temp = stream.ReadByte(); } if (response.ContentType == "image/jpeg") { result = bytes.ToArray(); } else { string errorResult = System.Text.Encoding.UTF8.GetString(bytes.ToArray()); if (errorResult.IndexOf("40001") != -1 && times < 3) { WxHelper.GetToken(webview_appid, webview_appsecret, true); times += 1; goto reGetToken; } } } string fileExtension = ".jpg"; if (result != null && result.Length > 0) { string ossurl = AliOSSHelper.GetOssImgKey(fileExtension.Replace(".", ""), false, out url); bool putResult = AliOSSHelper.PutObjectFromByteArray(ossurl, result, 1, fileExtension); if (putResult) { return(Json(new { isok = true, msg = url })); } else { return(Json(new { isok = false, msg = "保存失败" })); } } return(Json(new { isok = false, msg = "上传失败" })); }
public ActionResult uploadImageFromPost(int index = 0, bool isSave = false) { //var mediaId = Guid.NewGuid().ToString(); if (Request.Files.Count == 0) { return(Json(new BaseResult() { result = false, msg = "请选择一张图片" }, JsonRequestBehavior.AllowGet)); } using (Stream stream = Request.Files[0].InputStream) { string outext = "jpg"; byte[] imgByteArray = new byte[stream.Length]; stream.Read(imgByteArray, 0, imgByteArray.Length); // 设置当前流的位置为流的开始 stream.Seek(0, SeekOrigin.Begin); //开始上传图片 string aliTempImgKey = string.Empty; var aliTempImgFolder = AliOSSHelper.GetOssImgKey(outext, false, out aliTempImgKey); var putResult = AliOSSHelper.PutObjectFromByteArray(aliTempImgFolder, imgByteArray, 1, "." + outext); if (!putResult) { log4net.LogHelper.WriteInfo(this.GetType(), "图片上传失败!图片同步到Ali失败!mediaId"); return(Json(new { result = false, msg = "图片上传失败!图片同步到Ali失败!" }, JsonRequestBehavior.AllowGet)); } //添加到附件 //var pic = new Bitmap(stream); //var imgWidth = picWith > 0 ? picWith : pic.Width;//获取图片宽度 //var imgHeigth = picHeigth > 0 ? picHeigth : pic.Height; //获取图片高度 //var imgSize = 0; //切割缩略图 //var thumpath = Utility.AliOss.AliOSSHelper.GetAliImgThumbKey(aliTempImgKey, 200, 200); var thumpath = aliTempImgKey; //aliTempImgKey = aliTempImgKey.Replace("oss.", "img.") + $"@1e_1c_0o_0l_100sh_{imgHeigth}h_{imgWidth}w_90q.src"; Attachment model = new Attachment() { postfix = "." + outext, filepath = aliTempImgKey, thumbnail = thumpath //fid = minisnsId //imgsize = imgSize //userid = usermodel.Id }; var imgId = 0; if (isSave) { isSave = int.TryParse(AttachmentBll.SingleModel.Add(model).ToString(), out imgId); } return(Json(new { mediaId = imgId, path = aliTempImgKey, thumpath = thumpath, isSuccessSave = isSave, index = index }, JsonRequestBehavior.AllowGet)); } }
public async System.Threading.Tasks.Task <ActionResult> UploadVedioAsync() { try { var file = System.Web.HttpContext.Current.Request.Files[0]; if (file.InputStream.Length == 0) { return(Json(new { isok = false, msg = "上传失败,视频大小不能空", Path = "" }, JsonRequestBehavior.AllowGet)); } if (file.InputStream.Length > 20971520) { return(Json(new { isok = false, msg = "上传失败,视频文件不能超过20MB", Path = "" }, JsonRequestBehavior.AllowGet)); } string fileType = System.IO.Path.GetExtension(file.FileName).ToLower(); string[] VideoType = new string[] { ".mpeg4", ".mp4", ".mov", ".avi", ".wmv", ".3gp" }; if (!VideoType.Contains <string>(fileType.ToLower())) { return(Json(new { isok = false, msg = "不支持的格式,目前视频格式暂支持.mpeg4,.mp4,.mov,.avi,.wmv,.3gp" }, JsonRequestBehavior.AllowGet)); } byte[] byteData = new byte[file.InputStream.Length]; string tempurl = string.Empty; string tempkey = VideoAliMtsHelper.GetOssVideoKey(fileType.Replace(".", ""), true, out tempurl); Stream fileStream = file.InputStream; if (null != fileStream) { using (System.IO.BinaryReader br = new System.IO.BinaryReader(fileStream)) { byteData = br.ReadBytes(file.ContentLength); } } if (null == byteData) { log4net.LogHelper.WriteInfo(this.GetType(), "视频获取byte[]失败!"); return(Json(new { isok = false, msg = "系统错误!请联系管理员." })); } bool putrsult = AliOSSHelper.PutObjectFromByteArray(tempkey, byteData, 1, fileType.ToLower()); Tuple <string, string> pathDic = await C_AttachmentVideoBLL.SingleModel.GetConvertVideoPathAsync(tempkey); return(Json(new { isok = true, msg = "上传成功", videoconvert = pathDic.Item2, Vid = 0, soucepath = pathDic.Item1 })); } catch (Exception ex) { return(Json(new { isok = false, msg = "系统错误,请重新尝试" + ex.Message, Path = "" })); } }
public ActionResult UploadVoiceOnly() { try { var file = System.Web.HttpContext.Current.Request.Files[0]; if (file.InputStream.Length == 0) { return(Json(new { isok = false, msg = "上传失败,音频大小不能空", Path = "" })); } if ((file.InputStream.Length / 1024.0 / 1024.0) > 10) { return(Json(new { isok = false, msg = "上传失败,音频文件不能超过10M", Path = "" })); } if (!file.FileName.Substring(file.FileName.LastIndexOf(".")).Contains("mp3")) { return(Json(new { isok = false, msg = "上传失败,音频格式必须是MP3", Path = "" })); } byte[] byteData = new byte[file.InputStream.Length]; file.InputStream.Position = 0; file.InputStream.Read(byteData, 0, byteData.Length); file.InputStream.Close(); //将下载的语音放到AliOss临时文件夹 string voiceAliOssKey = string.Empty; //上传目录 string voiceAliOssFolder = AliOSSHelper.GetOssVoiceKey("mp3", true, "voice/folder", out voiceAliOssKey); bool putResult = AliOSSHelper.PutObjectFromByteArray(voiceAliOssFolder, byteData); if (!putResult)// 未能成功同步到AliOss { return(Json(new { isok = false, msg = "上传失败", Path = "" })); } return(Json(new { isok = true, msg = "上传成功", Path = voiceAliOssKey })); } catch (Exception) { return(Json(new { isok = false, msg = "系统错误,请重新尝试", Path = "" })); } }
/// <summary> /// 传图片,电脑发帖是附件 /// </summary> /// <param name="minisnsId"></param> /// <param name=domname></param> /// <param name="folder"></param> /// <param name="imageThumbnailUrl"></param> /// <param name="imgWidth"></param> /// <param name="imgHeigth"></param> /// <param name="imgSize"></param> /// <param name="postfix"></param> /// <param name="isWatermark"></param> /// <returns></returns> protected string uploadimg(byte[] byteData, out int imgWidth, out int imgHeigth, int imgSize, string postfix, bool istemp = true) { string msg = string.Empty; string BackUrl = "0"; imgWidth = 0; imgHeigth = 0; MemoryStream imgStreamWithWaterMark = null; try { postfix = "." + postfix.ToLower(); string aliTempImgKey = string.Empty; using (MemoryStream imgStream = new MemoryStream(byteData)) { using (imgStreamWithWaterMark = imgStream) { using (var image = new System.Drawing.Bitmap(imgStreamWithWaterMark)) { imgWidth = image.Width; imgHeigth = image.Height; if (postfix == "") { return("上传文件不能为空");//上传文件不能为空 } List <string> typelist = new List <string>() { ".gif", ".jpg", ".jpeg", ".png", ".bmp" }; if (!typelist.Contains(postfix)) { return("格式错误"); //格式错误! } if (imgSize > 20 * 1024 * 1024) { return("大小超出限制");//大小超出限制 } if (imgSize >= 5 * 1024 * 1024 && postfix != ".gif") { imgStreamWithWaterMark = Utility.ImgHelper.CompressImage(new System.Drawing.Bitmap(imgStreamWithWaterMark), Convert.ToInt32(imgWidth * 0.6), Convert.ToInt32(imgHeigth * 0.6), 100); } if (null != imgStreamWithWaterMark) { //同步到AliOss //上传的目录 var aliTempImgFolder = AliOSSHelper.GetOssImgKey(postfix.Replace(".", string.Empty), istemp, out aliTempImgKey); var byteArray = imgStreamWithWaterMark.ToArray(); var putResult = AliOSSHelper.PutObjectFromByteArray(aliTempImgFolder, byteArray, 1, postfix); if (!putResult) { log4net.LogHelper.WriteInfo(this.GetType(), "图片同步到Ali失败!"); } } else { Exception ex = new Exception("AliOss同步文件失败imgStreamWithWaterMark为null"); log4net.LogHelper.WriteError(this.GetType(), ex); return("{\"id\":\"-1\",\"imgUrl\":\"\"}"); } } } BackUrl = aliTempImgKey; } } catch (Exception ex) { log4net.LogHelper.WriteError(this.GetType(), ex); return("0"); } finally { if (null != imgStreamWithWaterMark) { imgStreamWithWaterMark.Dispose(); } } return(BackUrl); }
/// <summary> /// 此方法由APP调用。不可删除 /// </summary> /// <param name="context"></param> public void ProcessRequest(HttpContext context) { //因图文混排视频直接显示,设两个返回的临时视频地址 var reVideoUrl = string.Empty; var rePostUrl = string.Empty; context.Response.ContentType = "text/html"; string name = context.Request["name"]; HttpPostedFile file = context.Request.Files[name]; try { int minsnsId = 0; int.TryParse(context.Request["minsnsId"], out minsnsId); var tempurl = string.Empty; string fileExtension = System.IO.Path.GetExtension(file.FileName).ToLower(); int flag = 0;//标志是否需要转换 List <string> extents = new List <string> { ".mp4", ".ogg", ".mpeg4", ".webm", ".MP4", ".OGG", ".MPEG4", ".WEBM" }; string posterUploadDirectory = Path.Combine(ConfigurationManager.AppSettings["ImgUploadUrl4"], "videoposter", "mp4", DateTime.Now.Year.ToString(), DateTime.Now.Month.ToString()); var tempkey = VideoAliMtsHelper.GetOssVideoKey(fileExtension.Replace(".", ""), true, out tempurl); var byteData = new byte[file.ContentLength]; var fileStream = file.InputStream; if (null != fileStream) { using (System.IO.BinaryReader br = new System.IO.BinaryReader(fileStream)) { byteData = br.ReadBytes(file.ContentLength); } } if (null == byteData) { log4net.LogHelper.WriteInfo(this.GetType(), "视频获取byte[]失败!"); context.Response.Write(new JavaScriptSerializer().Serialize(new { result = 0, msg = "系统错误!请联系管理员." })); } var putrsult = AliOSSHelper.PutObjectFromByteArray(tempkey, byteData, 1, fileExtension.Replace(".", "")); if (extents.Contains(fileExtension)) { flag = 1; } VideoAttachment video = new VideoAttachment(); video.CreateDate = DateTime.Now; video.VideoSize = (file.ContentLength / (1024 * 1024.0)).ToString("N2");//单位为M //无需转换 if (1 == flag) { video.Status = 1; video.ConvertFilePath = VideoAliMtsHelper.GetUrlFromKey(tempkey.Replace("temp/", "")); } else { var regex = new Regex(@"(?i)\.[\S]*"); video.ConvertFilePath = VideoAliMtsHelper.GetUrlFromKey(regex.Replace(tempkey.Replace("temp/", ""), ".mp4")); video.Status = -2;//待转换 } video.UserId = int.Parse(context.Request.Form["UId"] ?? "0"); video.Fid = minsnsId; video.SourceFilePath = tempkey; int Vid = Convert.ToInt32(VideoAttachmentBLL.SingleModel.Add(video)); context.Response.Write(new JavaScriptSerializer().Serialize(new { result = "ok", msg = "上传成功", Vid = Vid })); } catch (Exception ex) { StringHelper.WriteOperateLog("error", ex.Message); context.Response.Write(""); } }
public static bool SaveImageToAliOSS(byte[] byteArray, out string aliTempImgKey) { string aliTempImgFolder = AliOSSHelper.GetOssImgKey("jpg", false, out aliTempImgKey); return(AliOSSHelper.PutObjectFromByteArray(aliTempImgFolder, byteArray, 1, ".jpg")); }
public ActionResult Image() { HttpFileCollection FileCollect = System.Web.HttpContext.Current.Request.Files; string ext = string.Empty; Stream imgStreamWithWaterMark = null; int cityid = Context.GetRequestInt("cityid", 0); if (FileCollect.Count > 0) { try { var file = FileCollect["upfile"]; Stream filestrem = file.InputStream; if (null != filestrem) { //var text = string.Empty; var city = new C_CityInfoBLL().GetModel(cityid); //if (null != city) //{ // text = city.CName; //} //添加水印 //imgStreamWithWaterMark = StreamHelpers.AddTextWatermark(filestrem, text); //if (null == imgStreamWithWaterMark) imgStreamWithWaterMark = filestrem;//添加水印失败就不添加水印,继续保存 }// 上传的文件为空 else { log4net.LogHelper.WriteInfo(this.GetType(), "fileStream为null!"); return(Json(new { state = "error", msg = "fileStream null" }, "text/x-json")); } imgStreamWithWaterMark.Position = 0;//保证流可读 byte[] byteData = StreamHelpers.ReadFully(imgStreamWithWaterMark); Utility.ImgHelper.IsImgageType(byteData, "jpg", out ext); //不是图片格式不让上传 string[] ImgType = new string[] { "jpg", "jpeg", "gif", "png", "bmp" }; if (!ImgType.Contains <string>(ext.ToLower())) { return(Json(new { state = "error", msg = "不支持的格式" }, "text/x-json")); } if (null != byteData) { //同步到AliOss string format = "." + ext; string aliImgKey; string aliTempImgFolder = AliOSSHelper.GetOssImgKey(ext, false, out aliImgKey); bool putResult = AliOSSHelper.PutObjectFromByteArray(aliTempImgFolder, byteData, 1, format); if (!putResult) { log4net.LogHelper.WriteInfo(this.GetType(), "图片同步到Ali失败!"); } return(Json(new { originalName = file.FileName, name = "", url = aliImgKey, size = file.ContentLength, state = "SUCCESS", type = format }, "text/x-json")); } else { return(Json(new { state = "error", msg = "byteData null" }, "text/x-json")); } } catch (Exception ex) { log4net.LogHelper.WriteError(this.GetType(), ex); return(Json(new { state = "error", msg = "runtime error" }, "text/x-json")); } finally { if (null != imgStreamWithWaterMark) { imgStreamWithWaterMark.Dispose(); } } } else { return(Json(new { state = "error", msg = "no data to upload" }, "text/x-json")); } }
public ActionResult UploadVoice() { try { var file = System.Web.HttpContext.Current.Request.Files[0]; if (file.InputStream.Length == 0) { return(Json(new { isok = false, msg = "上传失败,音频大小不能空", Path = "" }, JsonRequestBehavior.AllowGet)); } if ((file.InputStream.Length / 1024.0 / 1024.0) > 10) { return(Json(new { isok = false, msg = "上传失败,音频文件不能超过10M", Path = "" }, JsonRequestBehavior.AllowGet)); } if (!file.FileName.Substring(file.FileName.LastIndexOf(".")).Contains("mp3")) { return(Json(new { isok = false, msg = "上传失败,音频格式必须是MP3", Path = "" }, JsonRequestBehavior.AllowGet)); } int storeid = int.Parse(Context.GetRequest("storeid", "0")); int voicetype = Context.GetRequestInt("voicetype", (int)AttachmentItemType.小程序语音); byte[] byteData = new byte[file.InputStream.Length]; file.InputStream.Position = 0; file.InputStream.Read(byteData, 0, byteData.Length); file.InputStream.Close(); //将下载的语音放到AliOss临时文件夹 string voiceAliOssKey = string.Empty; //上传目录 string voiceAliOssFolder = AliOSSHelper.GetOssVoiceKey("mp3", true, "voice/folder", out voiceAliOssKey); bool putResult = AliOSSHelper.PutObjectFromByteArray(voiceAliOssFolder, byteData); if (!putResult)// 未能成功同步到AliOss { return(Json(new { isok = false, msg = "上传失败", Path = "" }, JsonRequestBehavior.AllowGet)); } List <C_Attachment> attachlist = C_AttachmentBLL.SingleModel.GetListByCache(storeid, voicetype); if (storeid > 0 && attachlist != null && attachlist.Count > 0) { C_AttachmentBLL.SingleModel.RemoveRedis(storeid, voicetype); return(Json(new { isok = true, msg = "上传成功", Path = voiceAliOssKey, voiceId = attachlist[0].id }, JsonRequestBehavior.AllowGet)); } else { C_Attachment attach = new C_Attachment(); attach.itemId = 0; attach.itemType = voicetype; attach.filepath = voiceAliOssKey; attach.createDate = DateTime.Now; attach.VoiceServerId = Guid.NewGuid().ToString(); attach.thumbnail = voiceAliOssKey; int voiceId = Convert.ToInt32(C_AttachmentBLL.SingleModel.Add(attach)); if (voiceId > 0) { return(Json(new { isok = true, msg = "上传成功", Path = voiceAliOssKey, voiceId = voiceId }, JsonRequestBehavior.AllowGet)); } } return(Json(new { isok = false, msg = "系统错误,请重新尝试", Path = "" })); } catch (Exception) { return(Json(new { isok = false, msg = "系统错误,请重新尝试", Path = "" })); } }
/// <summary> /// 更新店铺动态视频所属店铺动态id以及转移视频和图片-蔡华兴 /// </summary> /// <param name="videopath"></param> /// <param name="oldhvid"></param> /// <param name="strategyId"></param> /// <param name="videotype"></param> /// <returns></returns> public async Task <bool> HandleVideoLogicStrategyAsync(string videopath, int oldhvid, int strategyId, int videotype) { int result = 0; try { if (!string.IsNullOrEmpty(videopath)) { //清除老视频 if (oldhvid > 0) { C_AttachmentVideo cattV = GetModel(oldhvid); if (cattV != null) { Delete(oldhvid); RemoveRedis(cattV.itemId, cattV.itemType);//清除缓存 } } C_AttachmentVideo cVideo = new C_AttachmentVideo(); List <string> extents = new List <string> { "mp4", "ogg", "mpeg4", "webm", "MP4", "OGG", "MPEG4", "WEBM" }; string fileType = videopath.Substring(videopath.LastIndexOf('.') + 1); //判断是否需要转码 if (!extents.Contains(fileType)) { var regex = new Regex(@"(?i)\.[\S]*"); var tempconverpath = regex.Replace(videopath.Replace("temp/", "").Replace(fileType, "mp4"), ".mp4"); cVideo.convertFilePath = VideoAliMtsHelper.GetUrlFromKey(tempconverpath); //转码 await VideoAliMtsHelper.SubMitVieoJob(videopath, cVideo.convertFilePath); //获取封面图 var videoImgUrl = string.Empty; var videoImgKey = AliOSSHelper.GetOssImgKey("jpg", false, out videoImgUrl); await VideoAliMtsHelper.SubMitVieoSnapshotJob(tempconverpath, videoImgKey); cVideo.itemId = strategyId; cVideo.status = 1; cVideo.createDate = DateTime.Now; cVideo.itemType = videotype; //; cVideo.sourceFilePath = videopath; //视频路径 cVideo.videoPosterPath = videoImgUrl; //封面 result = Convert.ToInt32(Add(cVideo)); } else { var videokey = videopath.Replace("temp/", ""); //临时目录移动 var moveResult = AliOSSHelper.CopyObect(videopath, videokey, ".mp4"); if (!moveResult) { return(false); } //AliOss视频copy成功 else { //获取封面图 var videoImgUrl = string.Empty; var videoImgKey = AliOSSHelper.GetOssImgKey("jpg", false, out videoImgUrl); await VideoAliMtsHelper.SubMitVieoSnapshotJob(videokey, videoImgKey); cVideo.itemId = strategyId; cVideo.status = 1; cVideo.createDate = DateTime.Now; cVideo.itemType = videotype; cVideo.sourceFilePath = videokey;//视频路径 var regex = new Regex(@"(?i)\.[\S]*"); cVideo.convertFilePath = VideoAliMtsHelper.GetUrlFromKey(regex.Replace(videopath.Replace("temp/", ""), ".mp4")); cVideo.videoPosterPath = videoImgUrl;//封面 result = Convert.ToInt32(Add(cVideo)); } } } } catch (Exception) { } return(result > 0); }
//更新店铺时语音转mp3 public async Task <string> SendVoiceToAliOss(int voiceId, int artId, int commentId, string content = "", bool needUpdateContent = false, bool isupdate = false) { string artcont = content; if (voiceId < 1) { return(string.Empty); } C_Attachment model = GetModel(voiceId); if (model == null) { return(string.Empty); } model.itemId = artId; try { if (!string.IsNullOrEmpty(model.filepath)) { if (isupdate) { if (!model.filepath.Contains("temp"))//不是新上传的,停止操作! { log4net.LogHelper.WriteInfo(this.GetType(), "观察日志:修改文章停止旧语音移动。文章ID=" + artId + "语音路径" + model.filepath); return(string.Empty); } } var bucket = ConfigurationManager.AppSettings["BucketName"]; int whichDomain = 1; string TemplateId = string.Empty; string PipelineId = string.Empty; TemplateId = ConfigurationManager.AppSettings["VoiceTemplateId"] ?? "42d5aac40e6a50bf13045a40aeb83b6f"; PipelineId = ConfigurationManager.AppSettings["PipelineId"] ?? "4bc9dd15cb3d48e39e0824e19c41defb"; var finalVoiceKey = string.Empty; var finalVoiceFolder = AliOSSHelper.GetOssVoiceKey("mp3", false, "voice/folder", out finalVoiceKey, whichDomain); //上传的本地音频。并且不是mp3|| 微信语音 if (!string.IsNullOrEmpty(model.VoiceServerId)) { //转换mp3 bool submitResult = await AliMTSHelper.SubmitJobs(model.filepath, finalVoiceKey, bucket, TemplateId, PipelineId, "", whichDomain); if (submitResult) {//转换成功。更新路径 model.thumbnail = finalVoiceKey; //图文混排内容里的音频替换 if (needUpdateContent) { var voiceurl = model.filepath; artcont = CRegex.Replace(artcont, voiceurl, finalVoiceKey, 0); } }//音频转换失败 else { log4net.LogHelper.WriteInfo(this.GetType(), "语音给AliOSS转换格式失败!ID为" + model.id + "==" + model.filepath); } }//mp3移动 else { //本地音频mp3格式从temp 拷贝 Task <bool> moveResult = Task <bool> .Factory.StartNew( () => { return(AliOSSHelper.CopyObect(model.thumbnail, finalVoiceKey)); } ); ; if (await moveResult) {//移动成功。更新路径 model.thumbnail = finalVoiceKey; //图文混排内容里的音频替换 if (needUpdateContent) { var voiceurl = model.filepath; artcont = CRegex.Replace(artcont, voiceurl, finalVoiceKey, 0); } } // 移动失败 else { log4net.LogHelper.WriteInfo(this.GetType(), "本地音频AliOSS临时文件夹移动到正式文件夹失败!ID为" + model.id); } } } MySqlParameter[] param = new MySqlParameter[] { new MySqlParameter("@itemId", artId), new MySqlParameter("@filepath", model.filepath), new MySqlParameter("@thumbnail", model.thumbnail), new MySqlParameter("@id", model.id) }; string sql = "update C_Attachment set itemId=@itemId,filepath=@filepath,thumbnail=@thumbnail where id=@id"; SqlMySql.ExecuteNonQuery(Utility.dbEnum.MINIAPP.ToString(), System.Data.CommandType.Text, sql, param); RedisUtil.Remove(string.Format(CImageKey, model.itemId, model.itemType)); RemoveRedis(model.itemId, model.itemType); return(artcont); } catch (Exception ex) { log4net.LogHelper.WriteError(this.GetType(), new Exception("voiceid" + model.id + "移动语音失败:" + ex.Message)); return(string.Empty); } }
public static string DownloadImage(int cityid, string imgUrl) { try { string postfix = string.Empty, filepath = string.Empty; if (imgUrl.Contains("http://mmbiz.qpic.cn")) { if (imgUrl.Contains("?")) { int start = imgUrl.IndexOf("?"); imgUrl = imgUrl.Substring(0, start); } } //上传原图的路径 WebRequest fileWebRequest = null; try { fileWebRequest = WebRequest.Create(imgUrl); } catch (Exception) { return(string.Empty); } //捕捉路径问题的返回错误 MemoryStream container = null; Stream imgStreamWithWaterMark = null; try { using (WebResponse fileWebResponse = fileWebRequest.GetResponse()) { container = new MemoryStream(); fileWebResponse.GetResponseStream().CopyTo(container); container.Position = 0;//保证流可读 if (null != container && container.Length > 0) { string text = string.Empty; //var city = new C_CityInfoBLL().GetModel(cityid); //if (null != city) //{ // text = city.CName; //} //添加水印 //imgStreamWithWaterMark = Utility.IO.StreamHelpers.AddTextWatermark(container, text); if (null == imgStreamWithWaterMark) { imgStreamWithWaterMark = container; //添加水印失败就不添加水印,继续保存 } imgStreamWithWaterMark.Position = 0; //保证流可读 byte[] byteData = Utility.IO.StreamHelpers.ReadFully(imgStreamWithWaterMark); string ext; Utility.ImgHelper.IsImgageType(byteData, "jpg", out ext); string format = "." + ext; List <string> typelist = new List <string>() { ".gif", ".jpg", ".jpeg", ".png", ".bmp", ".riff" }; if (!typelist.Contains(format)) { return("notpic"); //格式错误! } if (ext == "riff") // 公众号文章图片格式 { ext = "jpg"; } string aliImgUrl = string.Empty; string aliOssImgName = string.Empty; string aliOssImgUrl = string.Empty; aliOssImgName = AliOSSHelper.GetOssImgKey(ext, false, out aliOssImgUrl); bool retult = AliOSSHelper.PutObjectFromByteArray(aliOssImgName, byteData, 1); if (retult) { return(aliOssImgUrl); } else { return(""); } } else { log4net.LogHelper.WriteInfo(typeof(CityCommonUtils), "自动抓取图片DownloadImage fileWebResponse.GetResponseStream() 为null"); } } } catch (Exception ex) { log4net.LogHelper.WriteError(typeof(Utility.Module), ex); return("notpic"); // 不是图片 } finally { if (null != container) { container.Dispose(); } if (null != imgStreamWithWaterMark) { imgStreamWithWaterMark.Dispose(); } } } catch (Exception ex) { log4net.LogHelper.WriteError(typeof(Utility.Module), ex); //跟踪一下为什么说URI格式错误 log4net.LogHelper.WriteInfo(typeof(Utility.Module), imgUrl); } return(""); }
public static void GetVoiceFromPath(ref Voices voice, string path) { Image img = null; FileInfo mp3File = null; Image waterPic = null; try { mp3File = new FileInfo(path); Mp3Lib.Mp3File mp3file = new Mp3Lib.Mp3File(mp3File); Id3Lib.TagHandler taginfo = new Id3Lib.TagHandler(mp3file.TagModel); voice.Singer = taginfo.Artist; // 歌手。 voice.Album = taginfo.Album; // 专辑。 voice.SongName = taginfo.Title; // 歌名。 //log4net.LogHelper.WriteInfo(typeof(Voices), string.Format("{0}:{1}:{2}", taginfo.Artist, taginfo.Album, taginfo.Title)); //ShellClass sh = new ShellClass(); //Folder dir = sh.NameSpace(Path.GetDirectoryName(path)); //FolderItem item = dir.ParseName(Path.GetFileName(path)); //voice.VoiceTime = string.IsNullOrEmpty(dir.GetDetailsOf(item, 27)) ? 0 : GetTimeSecond(dir.GetDetailsOf(item, 27)); // 获取歌曲时长。 //voice.Singer = dir.GetDetailsOf(item, 13); // 歌手。 //voice.Album = dir.GetDetailsOf(item, 14); // 专辑。 //voice.SongName = dir.GetDetailsOf(item, 21); // 歌名。 img = taginfo.Picture; if (img != null) { //string ImgUploadUrl = System.IO.Path.Combine(ConfigurationManager.AppSettings["ImgUploadUrl2"], "mp3", DateTime.Now.Year.ToString(), DateTime.Now.Month.ToString()); //string ImageUrl = ConfigurationManager.AppSettings["ImageUrl2"] + "mp3/" + DateTime.Now.Year.ToString() + "/" + DateTime.Now.Month.ToString(); Guid guid = Guid.NewGuid(); string fileName = guid.ToString() + ".jpg"; //if (!Directory.Exists(ImgUploadUrl)) //{ // Directory.CreateDirectory(ImgUploadUrl); //} // string savepath = Path.Combine(ImgUploadUrl, fileName); //if (!File.Exists(savepath)) //{ // img.Save(savepath); //} //封面图,传到OSS string aliTempImgKey = string.Empty; string songPic = AliOSSHelper.GetOssImgKey("jpg", false, out aliTempImgKey); byte[] imgBytes = Utility.ImgHelper.ImageToBytes(img); bool putResult = AliOSSHelper.PutObjectFromByteArray(songPic, imgBytes, 1, ".jpg"); voice.SongPic = songPic;// ImageUrl + "/" + fileName; //歌曲图片 //带播放水印的图片,传到OSS waterPic = Utility.ImgHelper.GetWaterPic(img); string aliTempImgKeySharePic = string.Empty; string SharePic = AliOSSHelper.GetOssImgKey("jpg", false, out aliTempImgKeySharePic); byte[] imgBytesSharePic = Utility.ImgHelper.ImageToBytes(waterPic); bool putResultSharePic = AliOSSHelper.PutObjectFromByteArray(SharePic, imgBytesSharePic, 1, ".jpg"); voice.SharePic = songPic; //Image waterPic = GetWaterPic(img); // if (!string.IsNullOrEmpty(waterPic)) // { // voice.SharePic = ImageUrl + "/" + waterPic; //分享图片 // } } if (mp3File != null) { //删除MP3文件 mp3File.Delete(); } } catch (Exception ex) { log4net.LogHelper.WriteError(typeof(Mp3Lib.Mp3File), ex); } finally { if (img != null) { img.Dispose(); } if (waterPic != null) { waterPic.Dispose(); } } }
public void ProcessRequest(HttpContext context) { context.Response.ContentType = "text/plain"; string name = context.Request["name"]; string serverid = ""; var fid = Utility.IO.Context.GetRequestInt("minsnsId", 0); var accid = Utility.IO.Context.GetRequest("accountId", ""); int voicetime = 0, voicetype = 0, convertstate = 0; int.TryParse(context.Request["voicetime"], out voicetime); int.TryParse(context.Request["voicetype"], out voicetype); if (voicetype == 1) //1录音文件 0本地音频 { serverid = "app_" + DateTime.Now.ToString(); //前端显示需要用到serverid convertstate = 1; // 前端显示需要用到 标识已转换成功 } Guid _accountId = Guid.Empty; try { if (string.IsNullOrEmpty(accid)) { accid = CookieHelper.GetCookie("UserCookieNew"); } _accountId = Guid.Parse(accid); } catch (Exception) { log4net.LogHelper.WriteInfo(this.GetType(), "guid转换失败,上传音频_accountId=" + accid); context.Response.Write(new JavaScriptSerializer().Serialize(new { result = 0, msg = "账号信息错误!" })); } /*如果有openId,发帖人用微信帐号 xiaowei 2015-10-27 11:21:54*/ Account account = AccountBLL.SingleModel.GetModel(_accountId); if (null == account) { context.Response.Write(new JavaScriptSerializer().Serialize(new { result = 0, msg = "账号信息错误!" })); } OAuthUser artUser = null; int userid = 0; if (null != account && !string.IsNullOrEmpty(account.OpenId)) { artUser = new OAuthUserBll(fid).GetUserByOpenId(account.OpenId, fid); userid = artUser.Id; } HttpPostedFile file = context.Request.Files[name]; string time = string.Empty; string fileType = System.IO.Path.GetExtension(file.FileName).ToLower(); List <string> extents = new List <string> { ".cda", ".wav", ".mp3", ".wma", ".ra", ".midi", ".ogg", ".ape", ".flac", ".aac", ".amr" }; if (!extents.Contains(fileType)) { context.Response.Write(new JavaScriptSerializer().Serialize(new { result = 0, msg = "音频格式不对" })); } int convertState = 1; var size = file.ContentLength; string aliTempImgKey = string.Empty; if (fileType != ".mp3") { convertState = -9; } var filePath = @"\\share3.vzan.cc\share\temp\pc" + DateTime.Now.ToFileTime().ToString() + fileType; file.SaveAs(filePath); var fileStream = file.InputStream; var byteData = new byte[size]; if (null != fileStream) { using (System.IO.BinaryReader br = new System.IO.BinaryReader(fileStream)) { byteData = br.ReadBytes(size); } //同步到AliOss //上传的目录 var aliTempImgFolder = AliOSSHelper.GetOssVoiceKey(fileType.Replace(".", ""), true, "voice/folder", out aliTempImgKey); var putResult = AliOSSHelper.PutObjectFromByteArray(aliTempImgFolder, byteData, 1, fileType); if (!putResult) { log4net.LogHelper.WriteInfo(this.GetType(), "语音同步到Ali失败!"); } }// 上传的文件为空 else { log4net.LogHelper.WriteInfo(this.GetType(), "fileStream为null!"); context.Response.Write(new JavaScriptSerializer().Serialize(new { error = aliTempImgKey, msg = "上传失败" })); } Voices voice = new Voices(); voice.ServerId = ""; voice.MessageText = ""; voice.DownLoadFile = aliTempImgKey; voice.TransFilePath = aliTempImgKey; voice.UserId = userid; voice.FId = fid; voice.VoiceTime = voicetime; voice.VoiceType = voicetype; voice.ServerId = serverid; //录音文件 voice.ConvertState = convertstate; //1 已转换 0为转换 voice.CreateDate = DateTime.Now; if (convertState == 1)//是mp3--获取音频信息必须保存到本地才能获得 { HostFile.GetVoiceFromPath(ref voice, filePath); } else { if (File.Exists(filePath)) { try { File.Delete(filePath); } catch (Exception) { } } } if (string.IsNullOrEmpty(voice.SongName)) { voice.SongName = file.FileName; } if (string.IsNullOrEmpty(voice.SongPic)) { voice.SongPic = "//j.vzan.cc/manager/images/yinping.jpg?v=0.1"; } int voiceId = Convert.ToInt32(VoicesBll.SingleModel.Add(voice)); if (voiceId > 0) { context.Response.Write(new JavaScriptSerializer().Serialize(new { result = 1, msg = "上传成功", time = voice.VoiceTime, url = aliTempImgKey, songpic = voice.SongPic, songname = voice.SongName, singer = voice.Singer, album = voice.Album, id = voiceId, createdate = voice.CreateDate.ToString("yyyy-MM-dd") })); } else { context.Response.Write(new JavaScriptSerializer().Serialize(new { result = 0, msg = "上传错误" })); } }
//更新店铺时语音转mp3 public async Task <string> SendVoiceToAliOss(int itemId, int itemType, string sourceTempUrl) { if (itemId <= 0 || itemType <= 0 || string.IsNullOrEmpty(sourceTempUrl)) { return(string.Empty); } C_Attachment model = GetModelByType(itemId, itemType); if (model == null) { model = new C_Attachment(); model.itemId = itemId; model.itemType = itemType; model.createDate = DateTime.Now; model.thumbnail = ""; } model.filepath = sourceTempUrl; try { if (!model.filepath.Contains("temp"))//不是新上传的,停止操作! { return(string.Empty); } var bucket = ConfigurationManager.AppSettings["BucketName"]; int whichDomain = 1; string TemplateId = string.Empty; string PipelineId = string.Empty; TemplateId = ConfigurationManager.AppSettings["VoiceTemplateId"] ?? "42d5aac40e6a50bf13045a40aeb83b6f"; PipelineId = ConfigurationManager.AppSettings["PipelineId"] ?? "4bc9dd15cb3d48e39e0824e19c41defb"; var finalVoiceKey = string.Empty; var finalVoiceFolder = AliOSSHelper.GetOssVoiceKey("mp3", false, "voice/folder", out finalVoiceKey, whichDomain); //上传的本地音频。并且不是mp3|| 微信语音 if (!string.IsNullOrEmpty(model.VoiceServerId)) { //转换mp3 bool submitResult = await AliMTSHelper.SubmitJobs(model.filepath, finalVoiceKey, bucket, TemplateId, PipelineId, "", whichDomain); if (submitResult) {//转换成功。更新路径 model.thumbnail = finalVoiceKey; }//音频转换失败 else { log4net.LogHelper.WriteInfo(this.GetType(), "语音给AliOSS转换格式失败!ID为" + model.id + "==" + model.filepath); } }//mp3移动 else { //本地音频mp3格式从temp 拷贝 Task <bool> moveResult = Task <bool> .Factory.StartNew( () => { return(AliOSSHelper.CopyObect(model.filepath ?? "", finalVoiceKey)); } ); if (await moveResult) {//移动成功。更新路径 model.thumbnail = finalVoiceKey; } // 移动失败 else { log4net.LogHelper.WriteInfo(this.GetType(), "本地音频AliOSS临时文件夹移动到正式文件夹失败!ID为" + sourceTempUrl); return(""); } } if (model.id == 0) { Add(model); } else { MySqlParameter[] param = new MySqlParameter[] { new MySqlParameter("@itemId", itemId), new MySqlParameter("@filepath", model.filepath), new MySqlParameter("@thumbnail", model.thumbnail), new MySqlParameter("@id", model.id) }; string sql = "update C_Attachment set itemId=@itemId,filepath=@filepath,thumbnail=@thumbnail where id=@id"; SqlMySql.ExecuteNonQuery(Utility.dbEnum.MINIAPP.ToString(), System.Data.CommandType.Text, sql, param); RemoveRedis(model.itemId, model.itemType); } return(""); } catch (Exception ex) { log4net.LogHelper.WriteError(this.GetType(), new Exception("voiceid" + model.id + "移动语音失败:" + ex.Message)); return(string.Empty); } }
/// <summary> /// 发帖成功后,视频处理,临时文件拷贝到正式文件, 如果要转码,需要进行转码 /// 目前一个视频附件只能有一个 /// </summary> /// <param name="itemId"></param> /// <param name="itemType"></param> /// <param name="videoKey"></param> /// <param name="cityInfoId"></param> public async Task <bool> HandleVideo(int itemId, int itemType, string videoKey_Org, int cityInfoId = 0) { var cVideo = GetModel($"itemId={itemId} and itemType={itemType}"); if (cVideo == null) { cVideo = new C_AttachmentVideo(); } cVideo.createDate = DateTime.Now; cVideo.itemId = itemId; cVideo.itemType = itemType;// (int)C_Enums.AttachmentVideoType.店铺动态视频; cVideo.sourceFilePath = videoKey_Org; cVideo.status = 1; cVideo.cityCode = cityInfoId; List <string> extents = new List <string> { "mp4", "ogg", "mpeg4", "webm", "MP4", "OGG", "MPEG4", "WEBM" }; string fileType = "mp4"; string[] keyExt = videoKey_Org.Split('.'); if (keyExt.Length > 1) { fileType = keyExt[1]; } //无需转换 , 直接COPY if (extents.Contains(fileType)) { var videokey = videoKey_Org.Replace("temp/", ""); //临时目录移动 var moveResult = AliOSSHelper.CopyObect(videoKey_Org, videokey, ".mp4"); cVideo.convertFilePath = VideoAliMtsHelper.GetUrlFromKey(videoKey_Org.Replace("temp/", "")); //AliOss视频copy成功 if (true == moveResult) { //获取封面图 var videoImgUrl = string.Empty; var videoImgKey = AliOSSHelper.GetOssImgKey("jpg", false, out videoImgUrl); await VideoAliMtsHelper.SubMitVieoSnapshotJob(videoKey_Org, videoImgKey); cVideo.videoPosterPath = videoImgUrl; } else { log4net.LogHelper.WriteInfo(typeof(VideoAttachmentBLL), "移动视频失败tempPath= " + videoKey_Org); } } else//需要转码 { var regex = new System.Text.RegularExpressions.Regex(@"(?i)\.[\S]*"); var convertUrl = VideoAliMtsHelper.GetUrlFromKey(regex.Replace(videoKey_Org.Replace("temp/", ""), ".mp4")); //提交给Ali转码 var covertResult = await VideoAliMtsHelper.SubMitVieoJob(videoKey_Org, convertUrl); cVideo.convertFilePath = convertUrl; if (covertResult) { //获取封面图 var videoImgUrl = string.Empty; var videoImgKey = AliOSSHelper.GetOssImgKey("jpg", false, out videoImgUrl); await VideoAliMtsHelper.SubMitVieoSnapshotJob(videoKey_Org, videoImgKey); cVideo.videoPosterPath = videoImgUrl; } else { log4net.LogHelper.WriteInfo(typeof(VideoAttachmentBLL), "提交转码视频失败tempPath= " + videoKey_Org); } } if (cVideo.id == 0) { Add(cVideo); } else { Update(cVideo); } return(true); }