ajax+ashx 完美實現input file上傳文件


1、input file 樣式不能滿足需求

 <input type="file" value="瀏覽" />

IE8效果圖:    Firefox效果圖: Chrome效果圖:  

2、input file上傳按鈕美化

css:    

.file{ position: relative; background-color: #b32b1b; border: 1px solid #ddd; width: 68px; height: 25px; display: inline-block; text-decoration: none; text-indent: 0; line-height: 25px; font-size: 14px; color: #fff; margin: 0 auto; cursor: pointer; text-align: center; border: none; border-radius: 3px;         
} .file input{ position: absolute; top: 0; left: -2px; opacity: 0; width: 10px;
}

html:  

<div>
    <span>選擇文件:</span><input id="txt_filePath" type="text" readonly="readonly"/>
    <a class="file"><input id="btnfile" name="btnfile" type="file"/>瀏覽</a>
</div>

美化后的效果圖:

 

3、ajax+ashx實現上傳功能

引入文件:jquery-1.11.3.js  ajaxfileupload.js

 js:

 $(function () { //選擇文件
            $(".file").on("change", "input[type='file']", function () { var filePath = $(this).val(); //設置上傳文件類型
                if (filePath.indexOf("xls") != -1 || filePath.indexOf("xlsx") != -1) { //上傳文件
 $.ajaxFileUpload({ url: 'ASHX/FileHandler.ashx', secureuri: false, fileElementId: 'btnfile', dataType: 'json', success: function (data, status) { //獲取上傳文件路徑
                            $("#txt_filePath").val(data.filenewname); alert("文件上傳成功!"); }, error: function (data, status, e) { alert(e); } }); } else { alert("請選擇正確的文件格式!"); //清空上傳路徑
                    $("#txt_filePath").val(""); return false; } }); })
FileHandler.ashx
public class FileHandler : IHttpHandler { public void ProcessRequest (HttpContext context) { context.Response.ContentType = "text/plain"; string msg = string.Empty; string error = string.Empty; string result = string.Empty; string filePath = string.Empty; string fileNewName = string.Empty; //這里只能用<input type="file" />才能有效果,因為服務器控件是HttpInputFile類型
        HttpFileCollection files = context.Request.Files; if (files.Count > 0) { //設置文件名
            fileNewName = DateTime.Now.ToString("yyyyMMddHHmmssff") + "_" + System.IO.Path.GetFileName(files[0].FileName); //保存文件
            files[0].SaveAs(context.Server.MapPath("~/Upload/"+fileNewName)); msg = "文件上傳成功!"; result = "{msg:'" + msg + "',filenewname:'" + fileNewName + "'}"; } else { error = "文件上傳失敗!"; result = "{ error:'" + error + "'}"; } context.Response.Write(result); context.Response.End(); } public bool IsReusable { get { return false; } } }

實現一個簡單上傳功能

 


免責聲明!

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



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