您的位置:首页 > 其它

[传智播客学习日记]一般处理程序之文件上传

2011-12-04 20:53 489 查看
<!--把文件上传到服务器的HTML代码,只能上传jpg格式-->
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
<script type="text/javascript">
function check() {
//获得要上传的文件的扩展名
var file = document.getElementById("up");
var value = file.value;
var ext = value.substr(value.lastIndexOf(".")+1);

//先在客户端进行第一次判断
if (ext == "jpg") {
return true;
} else {
alert("禁止");
return false;
}
}
</script>
</head>
<body>
<!--这里不要忘记enctype="multipart/form-data"属性-->
<form action="Handler.ashx" method="post" enctype="multipart/form-data">
<input type="file" id="up" name="upload" />
<input type="submit" value="上传" onclick="return check();" />
</form>
</body>
</html>


//把文件上传到服务器的服务端C#代码,只能上传jpg格式
<%@ WebHandler Language="C#" Class="Handler" %>

using System;
using System.Web;

public class Handler : IHttpHandler {

public void ProcessRequest (HttpContext context) {
context.Response.ContentType = "text/html";

//如果有文件
if (context.Request.Files.Count > 0)
{
//取到文件对象
HttpPostedFile file = context.Request.Files[0];
//取得文件后缀名(带个点)
string ext = System.IO.Path.GetExtension(file.FileName);

//判断上传文件的类型(jpeg),这里是根据文件头判断的,防止用户上传恶意假图
if (file.ContentType == "image/jpeg" || file.ContentType == "image/pjpeg")
{
//给文件取随及名
Random ran = new Random();
string fileName = DateTime.Now.ToString("yyyyMMddhhmmss") + ran.Next(100, 1000) + ext;

//保存文件
string path = context.Request.MapPath(fileName);
file.SaveAs(path);

//提示上传成功
context.Response.Write("上传文件:" + path);
}
}
//没有文件
else
{
context.Response.Write("上传错误!");
}
}

public bool IsReusable {
get {
return false;
}
}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: