文件_文件的上传及下载

====文件的上传====

新建一个html页 <form>标签的enctype属性要设置为enctype="multipart/form-data"

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title>文件的上传</title>
</head>
<body>
    <form method="post" action="上传Process.ashx" enctype="multipart/form-data" >
       选择文件:<input id="txtFileUpload" name="fileUpload" type="file" />
       <input type="submit" value="上传"  />
    </form>
</body>
</html>


添加一个一般处理程序

public class 上传Process : IHttpHandler {
    
    public void ProcessRequest (HttpContext context) {
        // 上传的文件
        HttpPostedFile uploadFile = context.Request.Files[0];
        // ’~/‘:当前网站根目录
        string savePath = context.Request.MapPath("~/文件上传下载/FileUpload/" + Guid.NewGuid().ToString() + uploadFile.FileName);
        try
        {
            uploadFile.SaveAs(savePath);
            context.Response.Write("文件上传成功");
        }
        catch (Exception ex)
        {


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


}


===文件的下载===

添加一个html页



<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title></title>
</head>
<body>
   
    <a href="下载Process.ashx">下载</a>
</body>
</html>


添加一个一般处理程序

using System;
using System.Web;


public class 下载Process : IHttpHandler {
    
    public void ProcessRequest (HttpContext context) {
         // 因为url为ASSIC码,必须对中文字进行Encode ,否则客户端看到的下载文件名为乱码
       
         string filePath = "~/文件上传下载/FileDownLoad/未标题-1_conew1.gif";
         string downLoadPath = HttpUtility.UrlEncode(filePath);


         // http 报文内容
         context.Response.AddHeader("Content-Disposition", string.Format("attachment;filename=\"{0}\"", downLoadPath));
        
        // 把文件的内容作为流输出
         context.Response.WriteFile(filePath);

        context.Response.Write("文件下载成功");
        
    }
 
    public bool IsReusable {
        get {
            return false;
        }
    }


}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值