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>

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM