htmL代码:
<div class="row">
<input type="file" name="fileToUpload" id="fileToUpload" onchange="fileSelected();"/>
</div>
<div id="fileSize"></div>
<div id="fileType"></div>
<div class="row">
<input type="button" onclick="uploadFile()" value="上传" />
</div>
<div id="progressNumber"></div>
<progress max="100" id="progre" value="0"></progress>
<br />
<asp:Image ID="Image1" Style="max-width:130px" runat="server" />
<asp:HiddenField ID="hfimg" value="" runat="server" />
JS代码:
<script type="text/javascript">
function fileSelected() {
var file = document.getElementById('fileToUpload').files[0];
if (file) {
var fileSize = 0;
if (file.size > 1024 * 1024)
fileSize = (Math.round(file.size * 100 / (1024 * 1024)) / 100).toString() + 'MB';
else
fileSize = (Math.round(file.size * 100 / 1024) / 100).toString() + 'KB';
document.getElementById('fileSize').innerHTML = '文件大小: ' + fileSize;
document.getElementById('fileType').innerHTML = '文件类型: ' + file.type;
}
}
function uploadFile() {
var fd = new FormData();
fd.append("fileToUpload", document.getElementById('fileToUpload').files[0]);
var xhr = new XMLHttpRequest();
xhr.upload.addEventListener("progress", uploadProgress, false);
xhr.addEventListener("load", uploadComplete, false);
xhr.addEventListener("error", uploadFailed, false);
xhr.addEventListener("abort", uploadCanceled, false);
xhr.open("POST", "/handler/h5upload.ashx");
xhr.send(fd);
function uploadProgress(evt) {
if (evt.lengthComputable) {
var percentComplete = Math.round(evt.loaded * 100 / evt.total);
document.getElementById('progressNumber').innerHTML = percentComplete.toString() + '%';
document.getElementById('progre').value = percentComplete;
else {
document.getElementById('progressNumber').innerHTML = 'unable to compute';
function uploadComplete(evt) {
/* This event is raised when the server send back a response */
var json =eval("("+ evt.target.responseText+")");
if (json.status=="no") {
alert(json.info);
}else{
document.getElementById("<%=Image1.ClientID%>").src = json.path;
document.getElementById("<%=hfimg.ClientID%>").value = json.path;
}
function uploadFailed(evt) {
alert("There was an error attempting to upload the file.");
function uploadCanceled(evt) {
alert("The upload has been canceled by the user or the browser dropped the connection.");
</script>
后台ashx代码:
context.Response.ContentType = "text/plain";
HttpPostedFile file =context. Request.Files["fileToUpload"];
String fileName = file.FileName;
String fileExt = Path.GetExtension(fileName).ToLower();
//定义允许上传的文件扩展名
Hashtable extTable = new Hashtable();
extTable.Add("image", "gif,jpg,jpeg,png,bmp");
extTable.Add("flash", "swf,flv");
extTable.Add("media", "swf,flv,mp3,wav,wma,wmv,mid,avi,mpg,asf,rm,rmvb");
extTable.Add("file", "doc,docx,xls,xlsx,ppt,htm,html,txt,zip,rar,gz,bz2");
if (String.IsNullOrEmpty(fileExt) || Array.IndexOf(((String)extTable["image"]).Split(','), fileExt.Substring(1).ToLower()) == -1)
{
context.Response.Write(LitJson.JsonMapper.ToJson(new { status="no", info = "上传文件扩展名是不允许的扩展名。
只允许" + ((String)extTable["image"]) + "格式。" }));
return;
string dirpath = "/upload/"+DateTime.Now.ToString("yyyyMMdd")+"/";
if (!Directory.Exists(context.Server.MapPath( dirpath)))
Directory.CreateDirectory(context.Server.MapPath(dirpath));
String newFileName = DateTime.Now.ToString("yyyyMMddHHmmss_ffff", DateTimeFormatInfo.InvariantInfo) + fileExt;
file.SaveAs(context.Server.MapPath(dirpath) + newFileName);
context.Response.Write(LitJson.JsonMapper.ToJson(new { status="ok",path = dirpath+newFileName}));