Html:
<div class="container">
<form id="form" runat="server" method="post" enctype="multipart/form-data" action="Upfile.ashx">
<span class="input-file" id="Filetransfer">
<img src="data:images/Filetransfer.png" style="z-index: -1; width: 100%; height: 100%;" />
<input class="fileInput" type="file" name="file1" id="file1" onchange="submitform()" />
</span>
</form>
</div>
script:
<script type="text/javascript" src="js/jquery-1.8.3.min.js"></script>
<script src="js/ajaxfileupload.js" type="text/javascript"></script>
<script type="text/javascript">
function submitform() {
if ($("#file1").val().length > 0) {
ajaxFileUpload();
}
else {
alert("请选择图片");
}
} function ajaxFileUpload() {
$.ajaxFileUpload
(
{
url: 'Upfile.ashx', //用于文件上传的服务器端请求地址
type: 'post',
fileElementId: 'file1', //文件上传空间的id属性 <input type="file" id="file" name="file" />
dataType: 'JSON', //返回值类型 一般设置为json
success: function (data, status) //服务器成功响应处理函数
{
$(".popupbox").show();
},
error: function (data, status, e)//服务器响应失败处理函数
{
alert(e);
}
}
)
return false;
} </script>
C#代码:
context.Response.ContentType = "text/plain";
System.Web.HttpFileCollection files =context.Request.Files;
for (int fileCount = 0; fileCount < files.Count; fileCount++)
{
System.Web.HttpPostedFile postedfile = files[fileCount]; string fileName = Guid.NewGuid().ToString().ToLower() + System.IO.Path.GetFileName(postedfile.FileName);
if (!String.IsNullOrEmpty(fileName))
{ string fileExtension = System.IO.Path.GetExtension(fileName); //获取文件类型
//上传目录
string nowtime = DateTime.Now.ToString("yyyy-MM-dd").Replace(" ", "_").Replace(":", "-");
string directory = System.Configuration.ConfigurationManager.AppSettings["k1"]+nowtime;
//文件全路径
string path = directory + "/" + fileName; //判断目录是否存在
if (!Directory.Exists(directory))
{
Directory.CreateDirectory(directory);
}
//文件存在就删除文件
if (File.Exists(path))
{
File.Delete(path);
}
//上传到服务器的路径
postedfile.SaveAs(path);
}
}