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