文件上传

来源:互联网 发布:java导出jar包 编辑:程序博客网 时间:2024/06/05 19:30

相关Html:

<form action="/" method="post" enctype="multipart/form-data"></form><input id="file" name="file" type="file" multiple="multiple" accept="image/png,image/jpeg,image/gif" value="上传文件" />


相关JS:

    $('#file').change(function () {         var files = this.files;//{{webkitRelativePath: "", lastModifiedDate: Wed Jul 09 2014 11:53:03 GMT+0800 (中国标准时间), name: "a0.jpg", type: "image/jpeg", size: 76825},...}        upload(files);        $.each(files, function (i, f) { //判断及供前端显示,实际上与上传无关            (function (i) {                var reader = new FileReader();                reader.onload = function (e) {                    console.log("src:" + e.target.result + "\r");                    if (files[i].size < 1024 * 1024 * 1024 * 8 && /image/.test(files[i].type)) {                                            }                };                reader.readAsDataURL(files[i]);                           })(i);        });    });    var isuploading = 0;    function upload(files) {        if (isuploading) return;        isuploading = 1;        var formData = new FormData();        var isComplete = false;        for (var i = 0; i < files.length; i++) formData.append("files[]", files[i]);                var xhr = new XMLHttpRequest();        xhr.open('post', '');        xhr.onload = function () { console.log("上传完成!"); };        xhr.onreadystatechange = function () {            if (xhr && xhr.readyState === 4) {                if (!isComplete && xhr.status >= 200 && xhr.status < 300 || xhr.status === 304) {                    isComplete = true;                    isuploading = 0;                    console.log(xhr.responseText);                                    } else if (!isComplete) {                    isComplete = true;                                        isuploading = 0;                    console.log("网络错误!");                }                xhr = null;            }        }        xhr.upload.onprogress = function (e) {            if (e.lengthComputable) {                var percent = (e.loaded / e.total * 100 | 0) + "%";                console.log(percent);            }        }        xhr.send(formData);    }

.net后台处理:

            for (int i = 0; i < Request.Files.Count; i++)            {                if (Request.Files[i].ContentLength <= 0) continue;                string path = AppDomain.CurrentDomain.BaseDirectory + "img/page/company/";                string filename = Path.GetFileName(Request.Files[i].FileName);                Request.Files[i].SaveAs(Path.Combine(path, new Random(~unchecked((int)DateTime.Now.Ticks)).Next(100, 999)+filename));                            }

参考:

http://achun.iteye.com/blog/1763771

http://www.cnblogs.com/studydotnet/archive/2010/05/03/1726778.html


html5 拍照 上传

<style>#video,#canvas {display: block;margin:1em auto;width:180px;height:180px;}#snap { display: block;margin:0 auto;width:80%;height:2em; }</style><div class="container">    <div>               <video id="video" autoplay></video>               <button id="snap">点击拍照</button>                <canvas id="canvas"></canvas>     </div></div><script>    window.addEventListener("DOMContentLoaded", function () {        try { document.createElement("canvas").getContext("2d"); } catch (e) { alert("not support canvas!") }        var video = document.getElementById("video"),            canvas = document.getElementById("canvas"),            context = canvas.getContext("2d");            navigator.getUserMedia = navigator.getUserMedia || navigator.webkitGetUserMedia || navigator.mozGetUserMedia || navigator.msGetUserMedia;        if (navigator.getUserMedia)            navigator.getUserMedia(                { "video": true },                function (stream) {                    if (video.mozSrcObject !== undefined)video.mozSrcObject = stream;                    else video.src = ((window.URL || window.webkitURL || window.mozURL || window.msURL) && window.URL.createObjectURL(stream)) || stream;                                   video.play();                },                function (error) {                    //if(error.PERMISSION_DENIED)console.log("用户拒绝了浏览器请求媒体的权限",error.code);                    //if(error.NOT_SUPPORTED_ERROR)console.log("当前浏览器不支持拍照功能",error.code);                    //if(error.MANDATORY_UNSATISFIED_ERROR)console.log("指定的媒体类型未接收到媒体流",error.code);                    alert("Video capture error: " + error.code);                }            );        else alert("Native device media streaming (getUserMedia) not supported in this browser");               $('#snap').on('click', function () {            context.drawImage(video, 0, 0, canvas.width = video.videoWidth, canvas.height = video.videoHeight);            $.post('/home/index', { "img": canvas.toDataURL().substr(22) }, function (data, status) {                if (status == "success") {                    if (data == "OK") alert("图片上传完成!");                                   }else alert("图片处理出错!");                           }, "text");        });    }, false); </script> 

c# .net MVC  后台处理:

        [HttpPost]        public ActionResult Index(FormCollection form)        {            try{                //将base64字符串转换为字节数组                byte[] imgBytes = Convert.FromBase64String(form["img"]);                //将字节数组转换为字节流                           System.IO.Stream stream = new System.IO.MemoryStream(imgBytes);                                    //将流转回Image,用于将PNG 式照片转为jpg,压缩体积以便保存。                         System.Drawing.Image imgae = System.Drawing.Image.FromStream(stream);                imgae.Save(System.Web.HttpContext.Current.Server.MapPath("~/") + Guid.NewGuid().ToString() + ".jpg", System.Drawing.Imaging.ImageFormat.Jpeg);//保存图片                return Content("OK");            }            catch (Exception e){ return Content(e.Message);}        }



参考:

http://bbs.9ria.com/thread-215588-1-1.html

http://blog.csdn.net/jin123wang/article/details/7413254

http://blog.sae.sina.com.cn/archives/1031

http://mozilla.com.cn/thread-45435-1-1.html

0 0
原创粉丝点击