码迷,mamicode.com
首页 > Web开发 > 详细

Ajax上传图片文件到服务器

时间:2017-05-13 16:05:32      阅读:724      评论:0      收藏:0      [点我收藏+]

标签:select   title   ace   整数   color   sts   使用   data   charset   

技术分享
 1 <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="FileUploadByJs.aspx.cs" Inherits="WebApplication1.UI.FileUploadByJs" %>
 2 
 3 <!DOCTYPE html>
 4 
 5 <html xmlns="http://www.w3.org/1999/xhtml">
 6 <head runat="server">
 7     <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
 8     <title></title>
 9     <script type="text/javascript" src="../JS/jquery.min.js"></script>
10     <script type="text/javascript">          
11         function Submit() {
12             var picPath = document.getElementById("imgFile").value;
13             if (picPath.trim() != "") {
14                 postFile(picPath);
15             }
16             else {
17                 alert("请先上传图片!");
18             }
19            
20         }
21         //判断文件是否是图片
22         function SelectImg() {
23             var picPath = document.getElementById("imgFile").value;
24             if (picPath.trim() != "") {
25                 var fileSuffix = picPath.substring(picPath.lastIndexOf(.) + 1, picPath.length);
26                 if (fileSuffix.toLowerCase() != jpg && fileSuffix.toLowerCase() != png) {
27                     alert("请上传图片文件!");
28                     return;
29                 }
30             }
31         }
32         //上传图片到服务器
33         function postFile(data) {
34             var d = {
35                 "imgUrl": data
36             }
37             $.ajax({
38                 url: "../AjaxHanlder/AjaxFileUploadHandler.ashx?action=FileUploadToServer",
39                 data: d,
40                 dataType: "JSON",
41                 async: false,
42                 success: function (msg) {
43                     if (msg != "上传出错!") {
44                         alert(msg);//返回图片路径
45                     }
46                     else {
47                         alert(msg);
48                     }
49                 },
50                 error: function () {
51                     alert("error");
52                 }
53             });
54         }
55     </script>
56 </head>
57 <body>
58     <form id="form1" runat="server">
59         选择要上传的图片:
60         <input type="file" name="file1" id="imgFile" onchange="SelectImg();" />
61         <br />
62         <input type="button" value="提交" id="submit" onclick="Submit();" />
63         <br />
64     </form>
65 </body>
66 </html>
前台
技术分享
 1 using System;
 2 using System.Collections.Generic;
 3 using System.Drawing;
 4 using System.Drawing.Imaging;
 5 using System.IO;
 6 using System.Linq;
 7 using System.Web;
 8 
 9 namespace WebApplication1.AjaxHanlder
10 {
11     /// <summary>
12     /// AjaxFileUploadHandler 的摘要说明
13     /// </summary>
14     public class AjaxFileUploadHandler : IHttpHandler
15     {
16 
17         public void ProcessRequest(HttpContext context)
18         {
19             context.Response.ContentType = "text/plain";
20             string action = context.Request.QueryString["action"];
21             switch (action)
22             {
23                 case "FileUploadToServer":
24                     FileUploadToServer(context);//上传图片到服务器
25                     break;
26                 default: break;
27             }
28         }
29 
30         private void FileUploadToServer(HttpContext context)
31         {
32             string imgUrl = context.Request.QueryString["imgUrl"].ToString() + "";
33             try
34             {
35                 MemoryStream s = new MemoryStream();
36                 Bitmap bitmap = new Bitmap(imgUrl);
37                 bitmap.Save(s, ImageFormat.Jpeg);
38                 s.Seek(0, SeekOrigin.Begin); 
39 
40                 //Stream s = new BufferedStream(context.Request.InputStream);
41                 byte[] bytes = new byte[s.Length];
42                 s.Read(bytes, 0, bytes.Length);
43 
44                 string name = Guid.NewGuid().ToString();
45                 string path = context.Server.MapPath("/uploads/" + name);
46                 File.WriteAllBytes(path, bytes);
47 
48                 ///取到当前时间的年、月、日、分、秒和毫秒的值,并使用字符串格式把它们组合成一个字符串
49                 String fileTime = DateTime.Now.Year.ToString() + DateTime.Now.Month.ToString()
50                     + DateTime.Now.Day.ToString() + DateTime.Now.Hour.ToString()
51                     + DateTime.Now.Second.ToString() + DateTime.Now.Minute.ToString()
52                     + DateTime.Now.Millisecond.ToString();
53                 ///在时间字符串后面添加一个随机数和文件的后缀名
54                 imgUrl = fileTime + GetRandomint() + Path.GetExtension(imgUrl);
55 
56                 string pathNew = context.Server.MapPath("/uploads/" + imgUrl);
57                 
58                 if (File.Exists(path))
59                 {
60                     File.Copy(path, pathNew, false);
61                     File.Delete(path);
62                 }
63                 context.Response.Write(pathNew);//上传成功,返回路径
64             }
65             catch (Exception ex)
66             {
67                 context.Response.Write("上传出错!");
68             }
69         }
70 
71         private String GetRandomint()
72         {
73             Random random = new Random();
74             return (random.Next(10000).ToString());    //产生一个小于10000的随机正整数
75         }
76 
77         public bool IsReusable
78         {
79             get
80             {
81                 return false;
82             }
83         }
84     }
85 }
后台

 

Ajax上传图片文件到服务器

标签:select   title   ace   整数   color   sts   使用   data   charset   

原文地址:http://www.cnblogs.com/lillyzou/p/6849083.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!