上传文件 | 下载文件

 HttpPostedFile 和 HttpPostedFileBase 你真的了解嘛?

上传文件


客户端:HtmlPage1.html

<!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>
    <!--上传文件的时候:
        1>必须使用Post方式来提交数据
        2>必须设置enctype属性值为multipart/form-data,表示将数据以二进制的方式提交到服务器;
        如果不设置的话enctype的默认值为application/x-www-form-urlencoded,表示将数据以键值对的方法是提交到服务器
    -->
    <form action="Handler1.ashx" method="post" enctype="multipart/form-data">
        <input type="file" name="fileName" value="" />
        <input type="submit"  value="上传"/>
    </form>
</body>
</html>

服务端:Handler1.ashx

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

namespace 上传文件
{
    /// <summary>
    /// Handler1 的摘要说明
    /// </summary>
    public class Handler1 : IHttpHandler
    {

        public void ProcessRequest(HttpContext context)
        {
            //设置报文头的content-type属性
            context.Response.ContentType = "text/plain";
            
            //获取浏览器发送过来的文件数据;
            HttpPostedFile file = context.Request.Files["fileName"];
       
            //获取上传的文件名。
            string fileName= file.FileName;

            
            //int fileLength = context.Request.ContentLength; 其实我们也可以获取文件的大小

            //取一个新的名字(在旧文件名前加上一个Guid就是为了防止上传的文件重名,产生冲突)
            string newfileName = Guid.NewGuid().ToString() + "_" + fileName;

            //将这个文件保存到项目下的files文件夹中
            file.SaveAs(context.Server.MapPath("files")+"/" + newfileName);

            context.Response.Write("OK");
        }

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





下载文件

客户端:HtmlPage1.html

<!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>
   <form>
       <a href="Handler1.ashx?fileName=123.jpg">123.jpg</a><br/>
       <a href="Handler1.ashx?fileName=abc.txt">abc.txt</a><br />
       <a href="Handler1.ashx?fileName=word.docx">word.docx</a><br />
       <a href="Handler1.ashx?fileName=介绍信模板.xls">介绍信模板.xls</a><br />
   </form>
</body>
</html>


服务端:Handler1.ashx

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

namespace 下载文件
{
    /// <summary>
    /// Handler1 的摘要说明
    /// </summary>
    public class Handler1 : IHttpHandler
    {

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

           

            //获取用户要下载的资源名称
            string filename = context.Request["fileName"];

            //添加报文头(请参考:http://blog.csdn.net/fanbin168/article/details/38535735)
            context.Response.AddHeader("Content-disposition", "attachment; filename=" +context.Server.UrlDecode( filename)); 

            //获取到用户要下载的资源后,读取磁盘文件,把该文件发送给客户端
            context.Response.WriteFile("~/Download/" + filename);

        }

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



批量文件上传



使用ploadify插件进行文件上传

在视图页面中使用uploadify插件,进行文件上传 (uploadify插件去官网:http://www.uploadify.com去下载)

参考资料:Uploadify/uploadifive上传(中文文档)

控制器

using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Web;
using System.Web.Mvc;

namespace WebApp.Controllers
{
    public class TestController : Controller
    {
        public ActionResult Index()
        {
            return View();
        }
        /// <summary>
        /// 文件上传
        /// </summary>
        /// <param name="Filedata"></param>
        /// <returns></returns>
        public ActionResult FilesUpload(HttpPostedFileBase Filedata)
        {
            // 如果没有上传文件
            if (Filedata == null ||string.IsNullOrEmpty(Filedata.FileName) ||Filedata.ContentLength == 0)
            {
                return this.HttpNotFound();
            }

            // 保存到 ~/zhaopian 文件夹中,名称不变
            string filename = System.IO.Path.GetFileName(Filedata.FileName);
            string virtualPath = string.Format("~/zhaopian/{0}", filename);
            // 文件系统不能使用虚拟路径,所以这里需要将虚拟路径转换成物理路径
            string path = this.Server.MapPath(virtualPath);

            //保存文件
            Filedata.SaveAs(path);
            return this.Json(new { });
        }
    }
}
视图

@{
    Layout = null;
}

<!DOCTYPE html>
<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>上传插件测试</title>
    @Scripts.Render("~/bundles/jquery")
    @Styles.Render("~/Content/css")

    <link href="~/Scripts/uploadify/uploadify.css" rel="stylesheet" />
    <script src="~/Scripts/uploadify/jquery.uploadify.js"></script>
</head>
<body>
    <input id="file_upload" name="file_upload" type="file" multiple="true">
</body>
</html>
<script type="text/javascript">
    $(function () {
        $("#file_upload").uploadify({
            swf: "/Scripts/uploadify/uploadify.swf",    //指定上传控件的主体文件
            uploader: "/Test/FilesUpload",   //指定服务器端上传处理文件
            width: 60,                          // 按钮的宽度
            height: 23,                         // 按钮的高度
            buttonText: "上传",                 // 按钮上的文字
            buttonCursor: 'hand',                // 按钮的鼠标图标
            fileObjName: 'Filedata',            // 上传参数名称

            // 两个配套使用
            fileTypeExts: "*.jpg;*.png",             // 扩展名
            fileTypeDesc: "请选择 jpg png 文件",     // 文件说明

            auto: true,                // 选择之后,自动开始上传
            multi: true,               // 是否支持同时上传多个文件
            queueSizeLimit: 5          // 允许多文件上传的时候,同时上传文件的个数

        });
    });
</script>


文件的下载(使用一般处理程序和MVC)

public class HomeController : Controller
{
    public ActionResult Index()
    {
        //SqlHelper.SqlBulkCopy();
        DataTable table = SqlHelper.ExecuteDataTable("select * from Table_1", null);
        var filePath = Server.MapPath("Excel/abc.xls");//设定要文件要保存的路径
        
        ExcelHelper.WriteExcel(table,filePath); //将DataTable表的数据写入到Excel文件中
        FileInfo info = new FileInfo(filePath); //读取刚刚保存的Excel文件
        long fileSize = info.Length; 
        Response.Clear(); 
        Response.ContentType = "application/octet-stream";
        Response.AddHeader("Content-Disposition", "attachement;filename=" + "abc.xls"); 
        //指定文件大小   
        Response.AddHeader("Content-Length", fileSize.ToString());  
        Response.WriteFile(filePath, 0, fileSize);  //将文件响应到浏览器
        Response.Flush();  
        Response.Close();

        return View();
    }
}





  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值