zoukankan      html  css  js  c++  java
  • html input type=file 文件上传; 图片上传; 图片闪烁

    (1)input file 对话框和 获取选中文件

    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    
    <html xmlns="http://www.w3.org/1999/xhtml">
    <head>
        <title>无标题页</title>
        <script type="text/javascript">
    function showPath(){//openfileDialog 和获取路径
        document.getElementById("path").innerText=document.getElementById("selFile").value;
    }
        </script>
    </head>
    <body>
    <input id="selFile" type="file" onchange ="showPath()"/>
    <div id="path"></div>
    </body>
    </html>

    (2)asp.net上传文件服务端脚本

    http://msdn.microsoft.com/en-us/library/system.web.ui.htmlcontrols.htmlinputfile.aspx

     客户端(.aspx)

    <%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="pages_Default" %>
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    
    <html xmlns="http://www.w3.org/1999/xhtml">
    <head runat="server">
        <title>上传图片</title>
    </head>
    <body>
        <form id="form1" runat="server">
        <div>选择要上传的文件<input id="File1" type="file" runat ="server" />
           <p>上传后的名称(不含拓展名)<input id="Text1" type="text" runat="server" /></p>
           <p><span id="Span1" style="font: 8pt verdana;" runat="server" /></p>
           <p>
           <input type="button" id="Button1" value="Upload" onserverclick="Button1_Click" runat="server" /></p>
        </div>
        </form>
    </body>
    </html>

    服务端

    using System;
    using System.Collections;
    using System.Configuration;
    using System.Data;
    using System.Linq;
    using System.Web;
    using System.Web.Security;
    using System.Web.UI;
    using System.Web.UI.HtmlControls;
    using System.Web.UI.WebControls;
    using System.Web.UI.WebControls.WebParts;
    using System.Xml.Linq;
    
    public partial class pages_Default : System.Web.UI.Page
    {
        protected void Button1_Click(object Source, EventArgs e)
        {
            int extIndex = File1.PostedFile.FileName.LastIndexOf('.');
            string ext =File1.PostedFile.FileName.Substring(extIndex);
            if (Text1.Value == "")
            {
                Span1.InnerHtml = "必须选择要上传的文件";
                return;
            }
    
            string dir = HttpContext.Current.Server.MapPath("../photos/buildings/");//设置在服务端的保存路径 MapPath("")获取的是页面在服务端的物理路径
            if (File1.PostedFile.ContentLength > 0)
            {
                try
                {
                    File1.PostedFile.SaveAs(dir + Text1.Value + ext);
                    Span1.InnerHtml = "File uploaded successfully to <b>" +dir+
                                       Text1.Value + ext + "</b> on the Web server.";
                }
                catch (Exception exc)
                {
                    Span1.InnerHtml = "Error saving file <b>" +dir+
                                       Text1.Value + ext + "</b><br />" + exc.ToString() + ".";
                }
            }
        }
    }

    (3)图片预览功能

    转载自:上善若水 http://www.cnblogs.com/load/archive/2012/03/06/2381657.html

    最近项目中用到的图片上传前预览功能,兼容IE6-9,FF
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
    <html xmlns="http://www.w3.org/1999/xhtml">
            <body>
                    <input type=file name="doc" id="doc" onchange="javascript:setImagePreview();">
    <p>
    <div id="localImag"><img id="preview" width=-1 height=-1 style="diplay:none" /></div>
    </p>
    <script>
    function setImagePreview() {
            var docObj=document.getElementById("doc");
     
            var imgObjPreview=document.getElementById("preview");
                    if(docObj.files &&    docObj.files[0]){
                            //火狐下,直接设img属性
                            imgObjPreview.style.display = 'block';
                            imgObjPreview.style.width = '300px';
                            imgObjPreview.style.height = '120px';                    
                            //imgObjPreview.src = docObj.files[0].getAsDataURL();
    
          //火狐7以上版本不能用上面的getAsDataURL()方式获取,需要一下方式  
          imgObjPreview.src = window.URL.createObjectURL(docObj.files[0]);
    
                    }else{
                            //IE下,使用滤镜
                            docObj.select();
                            var imgSrc = document.selection.createRange().text;
                            var localImagId = document.getElementById("localImag");
                            //必须设置初始大小
                            localImagId.style.width = "300px";
                            localImagId.style.height = "120px";
                            //图片异常的捕捉,防止用户修改后缀来伪造图片
    try{
                                    localImagId.style.filter="progid:DXImageTransform.Microsoft.AlphaImageLoader(sizingMethod=scale)";
                                    localImagId.filters.item("DXImageTransform.Microsoft.AlphaImageLoader").src = imgSrc;
                            }catch(e){
                                    alert("您上传的图片格式不正确,请重新选择!");
                                    return false;
                            }
                            imgObjPreview.style.display = 'none';
                            document.selection.empty();
                    }
                    return true;
            }
    </script>
    </body>
    </html>

    (4)静态页+handler实现上传功能

    页面和js

    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    <html xmlns="http://www.w3.org/1999/xhtml">
    <head>
        <title>添加楼房</title>
        <link rel="Stylesheet" href ="../css/AddBuilding.css" />
        <link rel="Stylesheet" href="../css/button.css" />
        <script type="text/javascript" src="../scripts/AddBuilding.js"></script>
    </head>
    <body onload ="getLocation()">
    <form action="../AddedHandlers/BuildingUnitRoomHandler.ashx?type=AddBuilding" method ="post" enctype="multipart/form-data">
    <input type="text" class="nodisplay" name="inpLocation" id="inpLocation"/>
    <div id="Left"><label>楼房名称</label><input type="text" name="BuildingName" id="BuildingName"/></br>
    <label>所在社区</label><input type="text" name="CommunityName" id="CommunityName"/></br>
    <p id="lbAddress"><span></br></br></br></br></br></span></p><textarea name="Address" id="Address"></textarea>
    </div>
    <div id="Right"><div id="localImag"><img id="Photo" alt="楼房照片" src="../images/尚未上传图片.jpg"/></div><p id="pBD"><input type="file" id="inpFile" name="inpFile" onchange ="checkFormat()"/><img id="imgDelete" alt="清空" title ="清空图片" src="../images/icons/PNG/onebit_33.png" onclick ="clearImage()"/></p></div>
    <div id="Bottom"><input type="submit" id="btnSave" class="normalButton" value="确定"/><input type="button" id="btnReturn" class ="normalButton" value="返回" onclick="javascript:close()"/></div>
    </form>
    </body>
    </html>
    window.onload =function(){ getLocation();}
    var formatchecker=true;
    function checkName(){
        if(document.getElementById("BuildingName").value==""){
            alert("建筑名称不能为空");
            return;
        }    
    }
    function clearImage(){
        document.getElementById("Photo").src="";
    }
    String.prototype.GetValue = function(parm) {
        var reg = new RegExp("(^|&)" + parm + "=([^&]*)(&|$)");
        var r = this.substr(this.indexOf("\?") + 1).match(reg);
        if (r != null) return unescape(r[2]); return null;
    }
    function getLocation(){//记录坐标
        document.getElementById("inpLocation").value=location.search.GetValue("Location");
    }
    function checkFormat(){
        var extIndex=document.getElementById("inpFile").value.lastIndexOf('.');
        var ext=document.getElementById("inpFile").value.substr(extIndex).toLowerCase();
        if(ext!=".jpg"&&ext!=".png"&&ext!=".bmp"&&ext!=".gif"&&ext!=".jpeg"){
            alert("只能上传jpg,png,bmp,gif,jpeg格式的图片");
            document.getElementById("Photo").src="../images/尚未上传图片.jpg";
            formatchecker=false;
            return;
        }
        formatchecker =true;
        setImagePreview();//预览图片
    }
    
    function setImagePreview() {//图片预览功能
            var docObj=document.getElementById("inpFile");
            var imgObjPreview=document.getElementById("Photo");
                    if(docObj.files &&    docObj.files[0]){
                            //火狐下,直接设img属性
                            imgObjPreview.style.display = 'block';
                            imgObjPreview.style.width = '300px';
                            imgObjPreview.style.height = '120px';                    
                            //imgObjPreview.src = docObj.files[0].getAsDataURL();
                    //火狐7以上版本不能用上面的getAsDataURL()方式获取,需要一下方式  
                     imgObjPreview.src = window.URL.createObjectURL(docObj.files[0]);
                    }else{
                            //IE下,使用滤镜
                            docObj.select();
                            var imgSrc = document.selection.createRange().text;
                            var localImagId = document.getElementById("localImag");
                            //必须设置初始大小
                            localImagId.style.width = "200px";
                            localImagId.style.height = "200px";
                            //图片异常的捕捉,防止用户修改后缀来伪造图片
            try{
                                    localImagId.style.filter="progid:DXImageTransform.Microsoft.AlphaImageLoader(sizingMethod=scale)";
                                    localImagId.filters.item("DXImageTransform.Microsoft.AlphaImageLoader").src = imgSrc;
                            }catch(e){
                                    alert("您上传的图片格式不正确,请重新选择!");
                                    return false;
                            }
                            imgObjPreview.style.display = 'none';
                            document.selection.empty();
                    }
                    return true;
            }

    handler获取文件

    else if (reqtype == "AddBuilding") {
                string buildingName = context.Request["BuildingName"].ToString();
                string communityName = context.Request["CommunityName"].ToString();
                string address=context.Request["Address"].ToString();
                string location = context.Request["inpLocation"].ToString();
                double longitude = Convert.ToDouble(location.Split(',')[0]);
                double latitude = Convert.ToDouble(location.Split(',')[1]);
                double altitude = Convert.ToDouble(location.Split(',')[2]);
                double heading = Convert.ToDouble(location.Split(',')[3]);
                double tilt = Convert.ToDouble(location.Split(',')[4]);
                double range = Convert.ToDouble(location.Split(',')[5]);
    
                HttpFileCollection hfc = HttpContext.Current.Request.Files;  //获取文件,保存图片
                HttpPostedFile hpf=hfc[0];
                int extIndex = hpf.FileName.LastIndexOf('.');
                string ext = hpf.FileName.Substring(extIndex);
                string fileName = Guid.NewGuid().ToString();
                string dir = HttpContext.Current.Server.MapPath("../photos/buildings/");
                hpf.SaveAs(dir + fileName+ext);
                BuildingUnit.AddBuilding(buildingName, longitude, latitude, altitude, heading, tilt, range, communityName, address, fileName+ext);
                return;
            }

    form的4个要点:

       (1)action指向handler?type   

       (2)method必须设置post

       (3)enctype="multipart/form-data"

       (4)INPUT type=file 元素必须出现在 form元素内。

    参考资料:http://www.hbcms.com/main/dhtml/objects/input_file.html

    5.图片闪烁功能

     原理:(1)setTimeout控制闪烁。 clearTimeout停止闪烁

             (2)每500ms,变更visibility实现显隐效果

    <html>
    <head>
    <script type="text/javascript">
    var c=0
    var t
    function timedCount()
    {
    document.getElementById('txt').value=c
    c=c+1
    t=setTimeout("timedCount()",1000)
    }
    
    function stopCount()
    {
    clearTimeout(t)
    }
    </script>
    </head>
    
    <body>
    <form>
    <input type="button" value="开始计时!" onClick="timedCount()">
    <input type="text" id="txt">
    <input type="button" value="停止计时!" onClick="stopCount()">
    </form>
  • 相关阅读:
    通过vue-cli命令行安装uni-app
    微信小程序中父子通信
    react启动问题
    react 父子通信
    windows下MongoDB的安装和启动服务--转载
    vue中使用骨架 vue-skeleton-webpack-plugin
    像企业一样思考
    Promise原理详解
    如何封装一个Cookie库
    你应该知道的浏览器缓存知识
  • 原文地址:https://www.cnblogs.com/imihiroblog/p/2708552.html
Copyright © 2011-2022 走看看