1500字范文,内容丰富有趣,写作好帮手!
1500字范文 > ajax+ashx 完美实现input file上传文件

ajax+ashx 完美实现input file上传文件

时间:2024-06-02 02:50:01

相关推荐

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;}}}

实现一个简单上传功能

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。