一般处理程序 —— 上传文件

 

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
    <title></title>
</head>
<body>
    <br /><br />
    <form action="上传文件.ashx" method="post" enctype="multipart/form-data">
        <input type="file" name="file1" />
        <input type="submit" value="上传JPG文件" />
    </form>
    <br /><br />
    <form action="上传Excel文件.ashx" method="post" enctype="multipart/form-data">
        <input type="file" name="file1" />
        <input type="submit" value="上传Excel文件" />
    </form>
</body>
</html>

上传图片,创建文件夹

using System;
using System.Collections.Generic;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Web;

namespace _2_一般处理程序
{
    /// <summary>
    /// 上传文件 的摘要说明
    /// </summary>
    public class 上传文件 : IHttpHandler
    {

        public void ProcessRequest(HttpContext context)
        {
            context.Response.ContentType = "text/html";
            HttpPostedFile file1 = context.Request.Files["file1"];
            context.Response.Write("<html><head><title>上传文件</title></head><body>");
            //是否上传文件
            if (file1.ContentLength <= 0)
            {
                context.Response.Write("请选择要上传的文件");
                OutputHtmlEnd(context.Response);
                return;
            }
            //上传文件大小检测
            if (file1.ContentLength > 1024 * 1024)
            {
                context.Response.Write("上传文件大小不能超过1M");
                OutputHtmlEnd(context.Response);
                return;
            }
            //上传文件后缀名检测
            string filename = file1.FileName;
            string suffix = Path.GetExtension(filename);
            if (suffix != ".jpg" & suffix != ".jpeg")
            {
                context.Response.Write("只允许上传jpg文件");
                OutputHtmlEnd(context.Response);
                return;
            }

            #region 保存文件
            //重命名:DateTime
            //Random ro = new Random();
            //filename = string.Format("{0}{1}{2}", DateTime.Now.ToString("yyyyMMddHHmmssff"), ro.Next(1000, 9999), suffix);

            //重命名:GUID(全球唯一标识符)推荐!!!
            filename = string.Format("{0}{1}", Guid.NewGuid().ToString("N"), suffix);

            //创建目录
            string dirPath = DateTime.Now.Year + "/" + DateTime.Now.Month + "/" + DateTime.Now.Day;
            string dirFullPath = context.Server.MapPath("~/upload/" + dirPath);
            string fileFullPath = Path.Combine(dirFullPath, filename);
            //如果文件夹不存在,则先创建文件夹
            if (!Directory.Exists(dirFullPath))
            {
                Directory.CreateDirectory(dirFullPath);
            }

            //string filePath = context.Server.MapPath("~/upload") + "/" + filename;
            
            //保存文件
            file1.SaveAs(fileFullPath);
            context.Response.Write("上传成功:" + fileFullPath);
            OutputHtmlEnd(context.Response);
            #endregion

            #region 加水印
            //using (Image img = Bitmap.FromStream(file1.InputStream))
            //{
            //    using (Graphics g = Graphics.FromImage(img))//得到图片的画布
            //    using (Font font = new Font(FontFamily.GenericSerif, 18))
            //    {
            //        g.DrawString("logo", font, Brushes.Red, 30, 0);
            //    }
            //    string fileName = DateTime.Now.ToString("yyyyMMdd");
            //    string filePath = context.Server.MapPath("~/upload") + "/" + fileName + extension;
            //    img.Save(filePath);
            //    context.Response.Write("上传成功:" + filePath);
            //} 
            #endregion
        }

        private void OutputHtmlEnd(HttpResponse response)
        {
            response.Write("</body></html>");
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
}

  上传Excel,读取Excel中的内容

using NPOI.SS.UserModel;
using NPOI.XSSF.UserModel;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web;

namespace _2_一般处理程序
{
    /// <summary>
    /// 上传Excel文件 的摘要说明
    /// </summary>
    public class 上传Excel文件 : IHttpHandler
    {

        public void ProcessRequest(HttpContext context)
        {
            context.Response.ContentType = "text/html";
            HttpPostedFile file1 = context.Request.Files["file1"];
            context.Response.Write("<html><head><title>Excel云</title></head><body>");
            //是否上传文件
            if (file1.ContentLength<=0)
            {
                context.Response.Write("请选择要上传的文件");
                OutputHtmlEnd(context.Response);
                return;
            }
            //上传文件大小检测
            if (file1.ContentLength > 1024 * 1024)
            {
                context.Response.Write("上传文件大小不能超过1M");
                OutputHtmlEnd(context.Response);
                return;
            }
            //上传文件后缀名检测
            string extension = Path.GetExtension(file1.FileName);
            if (extension != ".xls" & extension != ".xlsx")
            {
                context.Response.Write("只允许上传xls或xlsx文件");
                OutputHtmlEnd(context.Response);
                return;
            }

            using (Stream fs = file1.InputStream)
            {
                //自动识别Excel 2003或2007格式
                IWorkbook workbook = WorkbookFactory.Create(fs); 

                //遍历所有表
                for (int i = 0; i < workbook.NumberOfSheets; i++)
                {
                    ISheet sheet = workbook.GetSheetAt(i);
                    OutputSheet(context.Response, sheet);
                }
            }
        }

        private void OutputSheet(HttpResponse response, ISheet sheet)
        {
            response.Write("<h1>" + sheet.SheetName + "</h1>");
            response.Write("<table border='1'>");
            if (sheet.LastRowNum > 0)
            {
                //遍历所有行
                for (int j = sheet.FirstRowNum; j <= sheet.LastRowNum; j++)
                {
                    IRow row = sheet.GetRow(j);
                    if (row == null) continue;
                    response.Write("<tr>");
                    //遍历所有单元格
                    for (int k = row.FirstCellNum; k <= row.LastCellNum; k++)
                    {
                        ICell cell = row.GetCell(k);
                        string cellValue = (cell == null ? "" : cell.ToString());

                        response.Write("<td>" + cellValue + "</td>");

                    }
                    response.Write("</tr>");
                }
            }
            response.Write("</table>");
            OutputHtmlEnd(response);
        }

        private void OutputHtmlEnd(HttpResponse response)
        {
            response.Write("</body></html>");
        }
 

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
}

  

posted @ 2015-05-23 16:49  linyongqin  阅读(1087)  评论(0编辑  收藏  举报