1 <!--把文件上传到服务器的HTML代码,只能上传jpg格式-->
2 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
3 <html xmlns="http://www.w3.org/1999/xhtml">
4 <head>
5 <title></title>
6 <script type="text/javascript">
7 function check() {
8 //获得要上传的文件的扩展名
9 var file = document.getElementById("up");
10 var value = file.value;
11 var ext = value.substr(value.lastIndexOf(".")+1);
12
13 //先在客户端进行第一次判断
14 if (ext == "jpg") {
15 return true;
16 } else {
17 alert("禁止");
18 return false;
19 }
20 }
21 </script>
22 </head>
23 <body>
24 <!--这里不要忘记enctype="multipart/form-data"属性-->
25 <form action="Handler.ashx" method="post" enctype="multipart/form-data">
26 <input type="file" id="up" name="upload" />
27 <input type="submit" value="上传" onclick="return check();" />
28 </form>
29 </body>
30 </html>
1 //把文件上传到服务器的服务端C#代码,只能上传jpg格式
2 <%@ WebHandler Language="C#" Class="Handler" %>
3
4 using System;
5 using System.Web;
6
7 public class Handler : IHttpHandler {
8
9 public void ProcessRequest (HttpContext context) {
10 context.Response.ContentType = "text/html";
11
12 //如果有文件
13 if (context.Request.Files.Count > 0)
14 {
15 //取到文件对象
16 HttpPostedFile file = context.Request.Files[0];
17 //取得文件后缀名(带个点)
18 string ext = System.IO.Path.GetExtension(file.FileName);
19
20 //判断上传文件的类型(jpeg),这里是根据文件头判断的,防止用户上传恶意假图
21 if (file.ContentType == "image/jpeg" || file.ContentType == "image/pjpeg")
22 {
23 //给文件取随及名
24 Random ran = new Random();
25 string fileName = DateTime.Now.ToString("yyyyMMddhhmmss") + ran.Next(100, 1000) + ext;
26
27 //保存文件
28 string path = context.Request.MapPath(fileName);
29 file.SaveAs(path);
30
31 //提示上传成功
32 context.Response.Write("上传文件:" + path);
33 }
34 }
35 //没有文件
36 else
37 {
38 context.Response.Write("上传错误!");
39 }
40 }
41
42 public bool IsReusable {
43 get {
44 return false;
45 }
46 }
47
48 }