怎么用html5或js调用手机的摄像头拍照上传以及调用手机相册选取照片

JavaScript041

怎么用html5或js调用手机的摄像头拍照上传以及调用手机相册选取照片,第1张

1、实现头的方法代码。

2、编写CSS样式的方法代码。

3、html上传代码。

4、JS处理方法代码。

5、测试结果如下。

注意事项:

JavaScript是一种网络脚本语言,在web应用开发中得到了广泛的应用,它经常被用来为网页添加各种动态功能,为用户提供更加流畅美观的浏览效果,通常JavaScript脚本被嵌入到HTML中来实现自己的功能。

首先需要引用 js 和css

 <!--上传控件-->

2     <script src="query.form.min.js"></script>

3     <link href="Img_List.css" rel="stylesheet" />

4     <script src="Img_List.js"></script>

Img_List.js 如下:

/// <reference path="../../script/jquery-1.8.0.min.js" />

//显示

function imgshow(obj) {

    //$(obj).find("a").show()

}

//隐藏

function imghide(obj) {

    //$(obj).find("a").hide()

}

//上传

function upload() { 

    $("#FileLoad").click()

}

//删除

function imgdel(listId, FileId, hfId) {

    

    $.post("/CommonModule/ashx/public.ashx?action=DelMessageImg&Files=" + $("#" + hfId).val(), function (result) {

        if (result != "ok")

            $.messager.alert("消息提示", "删除失败!")

     })

    var html = "<li><img src=\"/Themes/Images/jia.jpg\" style=\"height: 80px width: 80px\" /><input type=\"file\" id=\""+FileId+"\" class=\"input\" onchange=\"ImgUpload('"+FileId+"','"+hfId+"','"+listId+"')\" name=\""+FileId+"\" /></li>"

    $("#"+listId).html(html)

}

//添加成功

function imgaddhtml(data, code,listId,fileId,hfId) {

    var list = data.split(',')

    var html = "<li onmouseover=\"imgshow(this)\" onmouseout=\"imghide(this)\">"

    html += "<a style=\"height:80pxwidth:80px\" href=\"" + list[0] + "\" target=\"_blank\"><img src=\"" + list[0] + "\" imgs=\"" + list[0] + "\" code=\"" + code + "\" /></a><span  onclick=\"imgdel('"+listId+"','"+fileId+"','"+hfId+"')\"></span></li>"

    $("#" + listId).html(html)

}

//图片文件上传

//uppath 上传空间id 

//上传成功存放的图片路径的隐藏域id

//listId 显示图片的区域id

function ImgUpload(uppath, hndimg,listId) {

    var sendUrl = "/CommonModule/ashx/Upload_Ajax.ashx?action=SingleFile&IsThumbnail=1&UpFilePath=" + uppath

    //开始提交

    $("#form1").ajaxSubmit({

        beforeSubmit: function (formData, jqForm, options) {

            //alert(1)

        },

        success: function (data, textStatus) {

            var list = $("#" + hndimg).val()

            $("#" + hndimg).val(data.msgbox)

            imgaddhtml(data.msgbox, 0,listId,uppath,hndimg)

        },

        error: function (data, status, e) {

            alert("上传失败!")

        },

        url: sendUrl,

        type: "post",

        dataType: "json",

        timeout: 600000

    })

}

Img_List.css 如下:

.img_list{ margin:0px padding:0px  overflow:hidden}

.img_list ul,.img_list ul li{ margin:0px padding:0px} 

.img_list ul li{ float:left list-style:none position:relative margin:5px 0px 0px 5px}

.img_list ul li span

{ position:absolutetop:3px right:3px width: 16px height: 16px opacity: 0.6filter: alpha(opacity=60) margin: 0 0 0 2px

vertical-align: top background: url('/Themes/Images/panel_tools.png') no-repeat -16px 0px}

.img_list ul li img{ width:80px height:80px cursor:pointer position:relative z-index:0}

.img_list ul li .input{ width:80px height:80px cursor:pointer position:relative left:-100pxvertical-align: top margin:0px padding:0px opacity:0filter: alpha(opacity=0) }

panel_tools.png 如下:

jia.jpg 如下:

前台页面代码:

<tr>

                        <th>图片1:</th>

                        <td>

                            <asp:Literal ID="ltrimg_list" runat="server"></asp:Literal>

                            <input type="hidden" runat="server" id="ImgPath" name="ImgPath" />

                            <span style="color:blue">建议尺寸(243*150)</span>

                        </td>

                    </tr>

<tr>

                        <th>图片2:</th>

                        <td>

                            <asp:Literal ID="Literal1" runat="server"></asp:Literal>

                          

                            <input type="hidden" runat="server" id="hkImgPath" name="hkImgPath" />

                             <span style="color:blue">建议尺寸(243*150)</span>

                        </td>

                    </tr>

后台初始化代码:

protected void Page_Load(object sender, EventArgs e)

        {

          

            if (!IsPostBack)

            {

               ltrimg_list.Text = UpLoad.showUploadFile("File1", "ImgPath", mfmodel.ImgPath, "img_list1")

                Literal1.Text = UpLoad.showUploadFile("File2", "hkImgPath", mfmodel.hkImgPath, "img_list2")

                   

            }

        }

        /// <summary>

        /// 生成一个上传插件信息

        /// </summary>

        /// <param name="fileId">上传控件id</param>

        /// <param name="hfId">隐藏域id用来保存上传的图片路径</param>

        /// <param name="imgUrl">初始化显示的图片地址</param>

        /// <param name="listId">上传成功之后用来显示上传图片的标签id</param>

        /// <returns></returns>

        public static string showUploadFile(string fileId, string hfId, string imgUrl, string listId)

        {

            string result = ""

            if (!string.IsNullOrEmpty(imgUrl))

            {

                result = "<div class=\"img_list\"><ul id=\"" + listId + "\"><li onmouseover=\"imgshow(this)\" onmouseout=\"imghide(this)\"><a style=\"height:80pxwidth:80px\" href=\"" + imgUrl + "\" target=\"_blank\"><img src=\"" + imgUrl + "\" imgs=\"" + imgUrl + "\" code=\"0\" /></a><span onclick=\"imgdel('" + listId + "','" + fileId + "','" + hfId + "')\"></span></li></ul></div>"

            }

            else

            {

                result = "<div class=\"img_list\"><ul id=\"" + listId + "\"><li><img src=\"/Themes/Images/jia.jpg\" style=\"height: 80px width: 80px\" /><input type=\"file\" id=\"" + fileId + "\"class=\"input\" onchange=\"ImgUpload('" + fileId + "','" + hfId + "','" + listId + "')\" name=\"" + fileId + "\" /></li></ul></div>"

            }

            return result

        }

上传方法:

#region 上传单文件处理===================================

 46         private void SingleFile(HttpContext context)

 47         {

 48 

 49             string _refilepath = context.Request.QueryString["ReFilePath"] //取得返回的对象名称

 50             string _upfilepath = context.Request.QueryString["UpFilePath"] //取得上传的对象名称

 51             string _delfile = context.Request.QueryString[_refilepath]

 52             HttpPostedFile _upfile = null

 53             try

 54             {

 55                 _upfile = context.Request.Files[_upfilepath]

 56             }

 57             catch (Exception e)

 58             {

 59                 context.Response.Write("{\"msg\": \"0\", \"msgbox\": \"上传文件过大!\"}")

 60                 context.Response.End()

 61             }

 62             bool _iswater = false //默认不打水印

 63             bool _isthumbnail = false //默认不生成缩略图

 64             bool _isimage = false

 65 

 66             if (context.Request.QueryString["IsWater"] == "1")

 67                 _iswater = true

 68             if (context.Request.QueryString["IsThumbnail"] == "1")

 69                 _isthumbnail = true

 70             if (context.Request.QueryString["IsImage"] == "1")

 71                 _isimage = true

 72 

 73             if (_upfile == null)

 74             {

 75                 context.Response.Write("{\"msg\": \"0\", \"msgbox\": \"请选择要上传文件!\"}")

 76                 return

 77             }

 78             UpLoad upFiles = new UpLoad()

 79             string msg = upFiles.fileSaveAs(_upfile, _isthumbnail, _iswater, _isimage)

 80             //删除已存在的旧文件

 81             Utils.DeleteUpFile(_delfile)

 82             //返回成功信息

 83             context.Response.Write(msg)

 84 

 85             context.Response.End()

 86         }

 87         #endregion

 

101         public string fileSaveAs(HttpPostedFile postedFile, bool isThumbnail, bool isWater, bool _isImage, bool _isReOriginal)

102         {

103             try

104             {

105                 string fileExt = Utils.GetFileExt(postedFile.FileName) //文件扩展名,不含“.”

106                 string originalFileName = postedFile.FileName.Substring(postedFile.FileName.LastIndexOf(@"\") + 1) //取得文件原名

107                 string fileName = Utils.GetRamCode() + "." + fileExt //随机文件名

108                 string dirPath = GetUpLoadPath() //上传目录相对路径

109 

110                 //检查文件扩展名是否合法

111                 if (!CheckFileExt(fileExt))

112                 {

113                     return "{\"msg\": \"0\", \"msgbox\": \"不允许上传" + fileExt + "类型的文件!\"}"

114                 }

115                 //检查是否必须上传图片

116                 if (_isImage && !IsImage(fileExt))

117                 {

118                     return "{\"msg\": \"0\", \"msgbox\":  \"对不起,仅允许上传图片文件!\"}"

119                 }

120                 //检查文件大小是否合法

121                 if (!CheckFileSize(fileExt, postedFile.ContentLength))

122                 {

123                     return "{\"msg\": \"0\", \"msgbox\":  \"文件超过限制的大小啦!\"}"

124                 }

125                 //获得要保存的文件路径

126                 string serverFileName = dirPath + fileName

127                 string serverThumbnailFileName = dirPath + "small_" + fileName

128                 string returnFileName = serverFileName

129                 //物理完整路径                    

130                 string toFileFullPath = Utils.GetMapPath(dirPath)

131                 //检查有该路径是否就创建

132                 if (!Directory.Exists(toFileFullPath))

133                 {

134                     Directory.CreateDirectory(toFileFullPath)

135                 }

136                 //保存文件

137                 postedFile.SaveAs(toFileFullPath + fileName)

138                 //如果是图片,检查图片尺寸是否超出限制

139                 if (IsImage(fileExt))

140                 {

141                     Thumbnail.MakeThumbnailImage(toFileFullPath + fileName, toFileFullPath + fileName, 3000, 3000)

142                 }

143                 //是否生成缩略图

144                 if (IsImage(fileExt) && isThumbnail)

145                 {

146                     Thumbnail.MakeThumbnailImage(toFileFullPath + fileName, toFileFullPath + "small_" + fileName, 150, 150, "R")

147                    // returnFileName += "," + serverThumbnailFileName //返回缩略图,以逗号分隔开

148                 }

149              

166                 /

171                 return "{\"msg\": \"1\", \"msgbox\": \"" + returnFileName + "\"}"

172             }

173             catch

174             {

175                 return "{\"msg\": \"0\", \"msgbox\":  \"上传过程中发生意外错误!\"}"

176             }

177         }