前端代码
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="RecUpload.aspx.cs" Inherits="ActivityFile_RecUpload" %>
<!DOCTYPE html>
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1" />
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>文件上传</title>
</head>
<body>
<form id="form1" runat="server" action="#" method="post" enctype="multipart/form-data">
<div style="margin-left: 20px; margin-top: 50px;">
选择照片:<input type="file" id="File" name="Task" style="margin-left: 5px; height: 25px;" />
<input type="button" value="上传" style="margin-left: 30px; height: 25px;" onclick="Upload()" />
</div>
</form>
<script type="text/javascript" src="../JavaScript/UserControl/jquery-1.4.2.min.js"></script>
<script type="text/javascript">
function Upload() {
var file = document.getElementById('File').files[0];
if (file != null) {
var fd = new FormData();
fd.append("File", file);
xhrupload(fd, "Url");
return false;
}
else {
alert("请选择需要上传的文件");
return false;
}
}
function xhrupload(fd, url) {
var xhr = new XMLHttpRequest();
xhr.open("post", url, true);
xhr.onreadystatechange = function () {
if (xhr.readyState == 4) {
if (200 == xhr.status) {
alert("上传成功");
document.getElementById('File').value = "";
}
else alert(xhr.responseText);
}
}
xhr.send(fd);
}
</script>
</body>
</html>
后台
string date = DateTime.Now.ToString("yyyyMMdd");
string filepath = HttpContext.Current.Server.MapPath("~/Files/Uploads/" + date + "");
string Name = Guid.NewGuid().ToString() + Type;
if (!Directory.Exists(filepath))
{
Directory.CreateDirectory(filepath);
}
HttpContext.Current.Request.Files[0].SaveAs(filepath + "\\" + Name);