上传文件的基本操作

 一、上传文件的前端代码比较简单,只需要在form表单中加入

enctype="multipart/form-data",然后就可以实现上传文件的操作
<!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>
    <!--enctype="multipart/form-data":如果要上传文件必须加上该属性,指定相应的编码。只有这样用户选择的文件数据(文件流)才会放在请求报文中,发送给服务器。表单中的其它表单元素(文本框等),也会发送到服务端,但是格式也变了,但是在服务端还是按照以前的方式进行接收-->
    <!--如果表单不需要上传文件就不用加  enctype="multipart/form-data"--->
    <!--<form method="post" action="ProcessFileUp.ashx" enctype="application/x-www-form-urlencoded">-->
    <form method="post" action="ProcessFileUp.ashx" enctype="multipart/form-data">
        <input type="file" name="fileUp" />
        <input type="text" name="txtName" />
        <input type="submit" value="上传" />

    </form>
</body>
</html>

二、后台代码相对比较多,主要是针对于处理文件的接收和保存,和多用户上传文件时,如何确定文件的唯一性,以及如何对文件更好的保存,而不会导致单一文件夹过大。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.IO;
namespace CZBK.ItcastProject.WebApp._2015_5_27
{
    /// <summary>
    /// ProcessFileUp 的摘要说明
    /// </summary>
    public class ProcessFileUp : IHttpHandler
    {

        public void ProcessRequest(HttpContext context)
        {
            context.Response.ContentType = "text/html";
           HttpPostedFile file=context.Request.Files[0];//获取上传的文件.
           if (file.ContentLength>0)
           {
               //对上传的文件类型进行校验。  单纯的file.FileName可能会获取到文件的路径
               string fileName =Path.GetFileName(file.FileName);//获取上传文件的名称包含扩展名。
               string fileExt = Path.GetExtension(fileName);//获取用户上传的文件扩展名。 如top1.jpg 的扩展名就是jpg
               if (fileExt == ".jpg")
               {
                   //1.对上传文件进行重命名?
                   string newfileName = Guid.NewGuid().ToString();  //生成一个唯一码
                   //2:将上传的文件放在不同的目录下面,获取当前日期的年月日
                   string dir = "/ImageUpload/"+DateTime.Now.Year+"/"+DateTime.Now.Month+"/"+DateTime.Now.Day+"/";
                   //创建文件夹
                   if (!Directory.Exists(context.Request.MapPath(dir)))
                   {
                       Directory.CreateDirectory(context.Request.MapPath(dir));
                   }

                   string fullDir = dir + newfileName + fileExt;//文件存放的完整路径。
                   file.SaveAs(context.Request.MapPath(fullDir));

                 //  file.SaveAs(context.Request.MapPath("/ImageUpload/"+fileName));//完成文件的保存。
                   context.Response.Write("<html><body><img src='"+fullDir+"'/></body></html>");
               }
               else
               {
                   context.Response.Write("只能上传图片文件");
               }
           }
           else
           {
               context.Response.Write("请选择上传文件");
           }
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
}
后台处理代码

 

posted @ 2019-02-20 21:37  锦大大的博客呀!  阅读(650)  评论(0编辑  收藏  举报