ImageUpload.html
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title></title>
<script src="../Scripts/jquery-1.7.1.js"></script>
<script type="text/javascript">
$(function () {
$(":file").change(function () {
var fileName = $(this).val();
var ext = fileName.substr(fileName.lastIndexOf('.'));
if (ext == ".jpeg" || ext == ".jpg" || ext == ".png" || ext == ".gif") {
return true;
} else {
$(this).val("");
}
});
});
</script>
</head>
<body>
<form method="POST" enctype="multipart/form-data" action="ImageUpload.ashx">
<input type="file" name="imgFile" />
<input type="submit" value="上传" />
</form>
</body>
</html>
ImageUpload.ashx
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web;
namespace WebDemo.Web.FileUpload
{
/// <summary>
/// ImageUpload 的摘要说明
/// </summary>
public class ImageUpload : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
context.Response.ContentType = "text/html";
HttpPostedFile file = context.Request.Files["imgFile"];
//后台也要校验。
string ext = Path.GetExtension(file.FileName);
if (!(ext == ".jpeg" || ext == ".jpg" || ext == ".png" || ext == ".gif"))
{
context.Response.End();
}
else
{
string path = "/Upload/" + Guid.NewGuid().ToString() + file.FileName;
file.SaveAs(context.Request.MapPath(path));
string str = string.Format("<html><head></head><body><img src='{0}'/></body></html>", path);
//把图片显示给用户
context.Response.Write(str);
}
}
public bool IsReusable
{
get
{
return false;
}
}
}
}
说点什么
欢迎讨论