mui保存视频 input保存视频 from保存文件

13 篇文章 0 订阅
13 篇文章 0 订阅

mui中选择了视频后和input选择的视频保存方法有一定的不一样来看代码:

选择视频这一段和选择图片一样,只是最后的文件类型不同而已。

var shiping = "";  //选择的视频(定义一个这东西保存的时候方便点)

function getImagefan() {  //录像
	var c = plus.camera.getCamera();
	c.startVideoCapture(function(e) {
		plus.io.resolveLocalFileSystemURL(e, function(entry) {
			var s = entry.toLocalURL() + "?version=" + new Date().getTime();
			xianshivideo(); //显示视频
			shiping = s;
			document.getElementById("head-img1").src = s;
			//变更大图预览的src
			//目前仅有一张图片,暂时如此处理,后续需要通过标准组件实现
			//document.querySelector("#__mui-imageview__group .mui-slider-item img").src = s + "?version=" + new Date().getTime();
		}, function(e) {
			console.log("读取拍照文件错误:" + e.message);
		});
	}, function(s) {
		console.log("error" + s);
	}, {
		filename: "_doc/head.jpg"
	})
}

function galleryImg() {  //选择视频
	plus.gallery.pick(function(a) {
		plus.io.resolveLocalFileSystemURL(a, function(entry) {
			plus.io.resolveLocalFileSystemURL("_doc/", function(root) {
				root.getFile("sp", {}, function(file) {
					//文件已存在
					file.remove(function() {
						//console.log("file remove success");
						entry.copyTo(root, 'sp', function(e) {
								var e = e.fullPath + "?version=" + new Date().getTime();
								xianshivideo(); //显示视频
								shiping = e;
								//$(".ceshibaocun").src('src',e);
								//console.log("看看"+$(".ceshibaocun")[0].src);
								document.getElementById("head-img1").src = e;
								//变更大图预览的src
								//目前仅有一张图片,暂时如此处理,后续需要通过标准组件实现
								document.querySelector("#__mui-imageview__group .mui-slider-item img").src = e + "?version=" + new Date().getTime();
							},
							function(e) {
								console.log('copy image fail:' + e.message);
							});
					}, function() {
						console.log("delete image fail:" + e.message);
					});
				}, function() {
					//文件不存在
					entry.copyTo(root, 'head.jpg', function(e) {
							var path = e.fullPath + "?version=" + new Date().getTime();
							xianshivideo(); //显示视频
							document.getElementById("head-img1").src = path;
							shiping = path;
							//变更大图预览的src
							//目前仅有一张图片,暂时如此处理,后续需要通过标准组件实现
							document.querySelector("#__mui-imageview__group .mui-slider-item img").src = path;
						},
						function(e) {
							console.log('copy image fail:' + e.message);
						});
				});
			}, function(e) {
				console.log("get _www folder fail");
			})
		}, function(e) {
			console.log("读取拍照文件错误:" + e.message);
		});
	}, function(a) {}, {
		filter: "video"  //!!!!!!!!!!!!!!!看这里就是这里和选择图片不一样
	})
};

//这个下面的显示视频对你们没用我就是写了个特效而已
function xianshivideo(){ //显示视频
	$(".huoqu-video").css("height","0px");
	$(".huoqu-video").css("width","0px");
	$(".shipingneirong").css("height","190px");
	$(".shipingneirong").css("width","290px");
	modify++; //判断这个页面有没有经过修改
}

这里来看看保存的JS代码
input:保存方式

 var reader = new FileReader();
   var video = shiping;//$("#main").prop('files')[0];  //选择的文件
console.log('=='+$("#main").prop('files')[0]);
   var rs = reader.readAsDataURL(video);  
   reader.onload = (e) =>{
     var videoSrc= e.target.result; 
     console.log(videoSrc)
     xccpost2("ShangLuCheng_API/video_shangchuangshiping",{video:videoSrc},function(erdata){
	if(erdata.code==200){
		
   }else{
	    mui.toast("正面上传出错");
    }
  });

mui:保存方式
mui这里选择到的视频和input标签里的不一样所以用不一样的方法

if(shiping.length < 1 || shiping == null){
    	mui.toast("您还未选择视频!");
    	return;
    }
    var data = JSON.parse(Base64.decode(GetRequest().data));  //简历ID
    var jianliid = data.jianliid; //传过来的数据
    $(".baocunann").css("margin-top","-46px");
    modify = 99;
    var task = plus.uploader.createUpload( httpurl2+"ShangLuCheng_API/video_shangchuangshiping",
		{ method:"POST",blocksize:0,priority:100 },
		function (t) {
			var huoquzifu =t.responseText; //返回过来的路径
			var reg = /^[\'\"]+|[\'\"]+$/g;  //用来去掉字符串前后的空格
			huoquzifu=huoquzifu.replace(reg,"");
			// 上传完成
			if (huoquzifu.length != 0 || t.length != 0) {
				xccpost2("ShangLuCheng_API/updatexiugaivideo",{jianliid:jianliid,VideoIntroduction:huoquzifu},function(shanchu){  //修改简历的视频
					if(shanchu.result=="200"){
						mui.toast("保存成功");
						$(".baocunann").css("margin-top","0px");
						modify = 0;
						//------------传值到父页面--------------(用来返回刷新)
						var openerPage = plus.webview.currentWebview().opener();
						mui.fire(openerPage,'shezhiname',{});
						setTimeout(function () {mui.back();},700);//延时返回
				        //------------end传值到父页面--------------
		            }else{
		            	mui.toast("背面保存失败");
		            }
			    },function(error){});
			} else { //这里就是失败了
				mui.toast("视频上传出现问题");
				$(".baocunann").css("margin-top","0px");
			}
		}
	);
	task.addFile( shiping, {key:"testdoc"} );
	task.addData( "string_key", "string_value" );
	//task.addEventListener( "statechanged", onStateChanged, false );
	task.start();
    

看看后台:(mui选择视频的写法)

public ActionResult video_shangchuangshiping()
        {
            try
            {
                int index = Convert.ToInt32(Request.Form["testdoc"]);
                var dir = Server.MapPath("~/Upload/video");
                dir = Path.Combine(dir);
                var baocunshu = DateTime.Now.Hour.ToString() + DateTime.Now.Minute.ToString() + DateTime.Now.Second.ToString() + ".mp4";
                string filePath = Path.Combine(dir, baocunshu);
                var data = Request.Files["testdoc"];
                if (data != null)
                {
                    data.SaveAs(filePath);
                }
                RS.code = 200;
                RS.data = "//Upload//video//"+ baocunshu;  //这里的路径别忘了
                return Json(RS.data, JsonRequestBehavior.AllowGet);
            }
            catch (Exception exc)
            {
                RS.code = 500;
                RS.message = exc.ToString();
                return Json(RS, JsonRequestBehavior.AllowGet);
            }
        }

看看后台:(input选择视频的写法)

        public ActionResult video_shangchuangshiping(string video)
        {
            string filename = "";//声明一个string类型的相对路径
            String base64 = video.Substring(video.IndexOf(",") + 1);      //将‘,’以前的多余字符串删除
            try
            {
                filename = DateTime.Now.Hour.ToString() + DateTime.Now.Minute.ToString() + DateTime.Now.Second.ToString() + ".mp4";//所要保存的相对路径及名字
                string tmpRootDir = Server.MapPath(System.Web.HttpContext.Current.Request.ApplicationPath.ToString()); //获取程序根目录 
                string imagesurl2 = tmpRootDir + "Upload\\video\\" + filename.Replace(@"/", @"\"); //转换成绝对路径 
                var contents = Convert.FromBase64String(base64);
                using (var fs = new FileStream(imagesurl2, FileMode.Create, FileAccess.Write))
                {
                    fs.Write(contents, 0, contents.Length);
                    fs.Flush();
                }
                RS.code = 200;
                RS.data = "//Upload//video//" + filename;
                return Json(RS, JsonRequestBehavior.AllowGet);
            }
            catch (Exception exc)
            {
                RS.code = 500;
                RS.message = exc.ToString();
                return Json(RS, JsonRequestBehavior.AllowGet);
            }
        }

别忘了把保存视频的路径创建了

if (Directory.Exists(Server.MapPath("~/Upload/video")) == false)//判断文件夹是否存在
                {
                    Directory.CreateDirectory(Server.MapPath("~/Upload/video"));//创建文件夹
                }

下面看看from保存文件
HTML

<li class="pdfshangchuang">  <!--这里用了一个比较好玩的css来隐藏input-->
			<h2>PDF简历</h2>
			<p>点击上传</p>
			<from id="formAttachment" action=""+httpurl2+"ShangLuCheng_API/Pdf_shangchuangshiping" method="post" enctypr="multipart/form-data">
			    <input type="file" name="file" accept="application/pdf" class="file-btn" placeholder="请上传" readonly/>
			</from>
		</li>

CSS

/*---上传pdf---*/
.pdfshangchuang{
	display: inline-block; 
	width:100%; 
	position: relative;
}
.pdfshangchuang p{
	float:right;
	line-height:50px;
	margin-right:10px;
	color:rgba(0,0,0,0.8);
	font-family:"黑体";
	font-size:15px;
}
.file-btn{
    position: absolute;
    width: 100%;
    height: 100%;
    top: 0;
    left: 0;
    outline: none;
    background-color: transparent;
    filter:alpha(opacity=0);-moz-opacity:0;-khtml-opacity: 0;opacity: 0;
}
/*---end上传pdf(目前还有点点看不懂)---*/

JQ

var files = $(".file-btn").prop('files');  //选择的文件
    var fd = new FormData();
    fd.append("file",files[0]);
    var xhr = new XMLHttpRequest();
    xhr.addEventListener("load",function(event){
    	console.log(event.currentTarget.responseText);
    	if(event.currentTarget.responseText!=null){
	    	xccpost2("ShangLuCheng_API/updatexiugaipdf",{jianliid:jianliid,PdfFile:event.currentTarget.responseText},function(erdata){
				if(erdata.result==200){
					if(ifchengg == 1){
						setTimeout(function () {mui.back();},1000);//延时返回
					}
			    }else{
				    mui.toast("上传PDF出现问题");
			    }
		    });
    	}else{
    	}
    },false)
    xhr.addEventListener("error",function(event){
    })
    xhr.open("POST",""+httpurl2+"ShangLuCheng_API/Pdf_shangchuangshiping")
    xhr.send(fd);

控制器:

#region 
        /// <summary>
        /// PDF上传
        /// </summary>
        /// <param name="httpimge"></param>
        /// <returns></returns>
        public ActionResult Pdf_shangchuangshiping(HttpPostedFileBase file)
        {
            try
            {
                if (Directory.Exists(Server.MapPath("~/Upload/pdf")) == false)//判断pdf文件夹是否存在
                {
                    Directory.CreateDirectory(Server.MapPath("~/Upload/pdf"));//创建pdf文件夹
                }
                //文件类型 后缀
                string fileExtension = Path.GetExtension(file.FileName);
                //不包含文件扩展名的名称 不带后缀
                string fileName = Path.GetFileNameWithoutExtension(file.FileName);
                //原始文件名称
                string oldFileName = file.FileName;
                //文件名称,添加时间字符串,避免文件名称相同 
                fileName = fileName + DateTime.Now.ToString("yyyy-MM-dd-HH-mm-ss-ffff") + fileExtension;

                //保存文件的路径
                string filePath = Server.MapPath("~/Upload/pdf/") + fileName;
                //保存文件
                if (file != null)
                {
                    file.SaveAs(filePath);
                }
                RS.code = 200;
                RS.data = "//Upload//pdf//" + fileName;
                return Json(RS.data, JsonRequestBehavior.AllowGet);
            }
            catch (Exception exe)
            {
                RS.code = 500;
                RS.message = exe.ToString();
                return Json(RS, JsonRequestBehavior.AllowGet);
            }
        }
        #endregion
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值