.Net文件上传和下载

1.前端控件代码

<!DOCTYPE html>
<html>
	<head>
		<meta charset="UTF-8">
		<title></title>
		<script src="js/jquery-3.4.1.min.js" type="text/javascript" charset="utf-8"></script>
	</head>
		<!--下载样式-->
	     <style>
 	       #FileDown:focus {
   	       outline:none;border: 2px solid  #C0C0C0;border-left: 5px solid rgb(0,139,229);
   	       }
   	       #FileDown{
   	       width: 500px;height: 30px;border: 1px solid #E7EAEC; border-left: 5px solid rgb(0,139,229);
   	       }
   	       </style>
   	       <!--上传样式-->
   	        <style>
   	       a[class="button-selectimg"] {
   	       color: black; padding: 4px 6px; background-color: rgb(0,139,229);border-radius: 2px; text-decoration: none;
   	       }
   	       input[id="avatval"] {
   	      	padding: 3px 6px; padding-left: 10px;border: 1px solid #E7EAEC; width: 500px;height: 29.8px; line-height: 25px;border-left: 7px solid rgb(0,139,229);background: #FAFAFB;border-radius: 2px;
   	       }
   	       input[type="file"] {
   	         border: 0px; display: none; 
   	       }
   	      #avatval:focus {
   	      outline:none;border: 2px solid  #FAFAFB;border-left: 5px solid rgb(0,139,229);
   	      }
   	      </style>
	<body>
			<div id="xiaZai">
				<input type="text" name="FileDown" placeholder="无可下载文件···" id="FileDown" value="" readonly="readonly" />
   	   			 <INPUT id="downFile" style="margin: 0px 0px 5px 0px;width: 100px;height: 30px;" class="l-btn-text btn c" value="下载文件" type="button"/>		
			</div>
			<div class="input-file">
		   	     <input type="text" id="avatval" placeholder="可选择上传文件···" readonly="readonly" />
		   	     <input type="file" name="avatar" id="avatar"/>
		   	     <INPUT id="upFile" style="margin: 0px 0px 5px 0px;width: 100px;height: 30px;" class="l-btn-text btn c" value="上传" type="button"/>
	   	     </div>
	   	     
	</body>
</html>
<!--
	文件上传点击input框事件
-->
<script type="text/javascript">
		function Get(){
			debugger
			var files = $('input[name="avatar"]').prop('files');
			alert(files);	
			var list=eval(files);
			for(var i=0;i<list.length;i++){
				alert(list[i].type)
			}
		}
        $(function(){
            
            $("#avatval").click(function(){
                $("input[type='file']").trigger('click');
            });
            $("input[type='file']").change(function(){
                $("#avatval").val($(this).val());
            });
       });
 </script>
 <!--下载事件-->
 <script type="text/javascript">
 	$("#downFile").click(function(){
 		var BillNo=BC_PS_SS_AppealBase.getFieldValue("BillNo");
		var EmpNo=UCML.UserInfo.getUserId();
		var isV="2";
		var url = UCMLLocalResourcePath+"ImgHandler.ashx?BillNo="+BillNo+"&isV="+isV+"&EmpNo="+EmpNo;
		window.open(url);
 	})
 </script>
 <!--上传事件-->
 <script type="text/javascript">
 	$("#upFile").click(function(){
	 	var files = $('input[name="avatar"]').prop('files');
		var flies=$('#avatar').get(0).files[0];
		var fileType="";
		var fileName="";
		var fileSize="";
		var isV="1";
		var list=eval(files);
		for(var i=0;i<list.length;i++){
		      fileType=list[i].type;
			  fileName=list[i].name;
			  fileSize=list[i].size;
		}
		var formData = new FormData();
		formData.append("fileType",fileType);//上传一个files对象
		formData.append("fileName",fileName);
		formData.append("fileSize",fileSize);
		formData.append("isV",isV);
		formData.append("file",$("#avatar").get(0).files[0]);
		$.ajax({//此处可以换成其它请求方式
			url: '../../ImgHandler.ashx',
			dataType: "json",
			type: "post",
			data: formData,
			processData: false,//不去处理发送的数据
			contentType: false,//不去设置Content-Type请求头
			error: function (res) {
				//alert(res.message);
				return;
			},
			success: function (res) {
				//alert(res.message);
				return;
			}
		})
 	})
 </script>

2.定义ImgHandler.ashx页面(页面代码)

<%@ WebHandler Language="C#" CodeBehind="ImgHandler.ashx.cs" Class="UCMLCommon.ImgHandler" %>

3.定义ImgHandler.ashx.cs类(类后端代码)

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Newtonsoft.Json;
using System.Data.SqlClient;
using Newtonsoft.Json.Linq;
using Newtonsoft.Json;
using System.IO;
using System.Threading;
 
namespace UCMLCommon
{
 
    public enum CodeStatus
    {
        error = 0,
        success = 1
    }
 
    public class Message
    {
        //1:成功  0:失败
        public int code { get; set; }
        public string message { get; set; }
 
 
        public Message(CodeStatus code, string message)
        {
            this.code = (int)code;
            this.message = message;
        }
 
    }
 
    /// <summary>
    /// ImgHandler 的摘要说明
    /// PM_ProduceSignSampleImg图片上传
    /// </summary>
    public class ImgHandler : IHttpHandler
    {
 
        public void ProcessRequest(HttpContext context)
        {
            //返回信息
            Message meg = new Message(CodeStatus.error, "");
 
            HttpFileCollection files = context.Request.Files;//获取文件信息
           
 
            var fileName = context.Request.Params["fileName"];
            var BillNo = context.Request.Params["BillNo"];
            var EmpNo = context.Request.Params["EmpNo"];
            var fileSize = context.Request.Params["fileSize"];
            var NodeEmpOID = "";
            var isV = context.Request.Params["isV"];
            var isSava = 0;//判断是否存在该记录文件
            //DAL
            DBLayer.PS_BS_Employee dal = new DBLayer.PS_BS_Employee();
            Thread.Sleep(100);
            if (BillNo != "" && EmpNo != "")
            {
                string data = @" select COUNT(*) as isSava,PS_SS_AppealNodeEmpOID from PS_SS_Appeal Appeal inner join PS_SS_AppealNode Node on Appeal.PS_SS_AppealOID=Node.PS_SS_Appeal_FK
                inner join PS_SS_AppealNodeEmp Emp on Node.PS_SS_AppealNodeOID=Emp.PS_SS_AppealNode_FK
                where BillNo='" + BillNo + "' and  FlowNode=1 and OpUser='" + EmpNo + "' group by PS_SS_AppealNodeEmpOID";
                string DataNodeEmpOID = JsonConvert.SerializeObject(dal.ExecuteQuery(data));
                JArray DataNodeEmpOIDs = (JArray)JsonConvert.DeserializeObject(DataNodeEmpOID);
                for (int i = 0; i < DataNodeEmpOIDs.Count; i++)
                {
                    NodeEmpOID = DataNodeEmpOIDs[i]["PS_SS_AppealNodeEmpOID"].ToString();
                }
 
                string sqlIsSava = @" select COUNT(*) as isSava from PS_SS_AppealNodeEmpAtt Att inner join PS_SS_AppealNodeEmp Emp on Att.PS_SS_AppealNodeEmp_FK=Emp.PS_SS_AppealNodeEmpOID
				inner join PS_SS_AppealNode Node on Emp.PS_SS_AppealNode_FK=Node.PS_SS_AppealNodeOID 
				inner join PS_SS_Appeal Appeal on Node.PS_SS_Appeal_FK=Appeal.PS_SS_AppealOID
				where Appeal.BillNo='" + BillNo + "' and Node.FlowNode=1 and Emp.OpUser='" + EmpNo + "'";
                string DataIsSava = JsonConvert.SerializeObject(dal.ExecuteQuery(sqlIsSava));
                JArray DataIsSavas = (JArray)JsonConvert.DeserializeObject(DataIsSava);
                for (int i = 0; i < DataIsSavas.Count; i++)
                {
                    isSava = Convert.ToInt32(DataIsSavas[i]["isSava"]);
                }
            }
 
            if (isV == "1")//上传
            {
                HttpPostedFile uploadFile = context.Request.Files[0];
                var OID = Guid.NewGuid().ToString();
                #region 文件上传
                if (files.Count != 0)
                {
                    try
                    {
                        var TypeList = fileName.Split('.');
                        var fileType = "." + TypeList[1];
                        var pathUrls = Path.GetFileName(files[0].FileName);
                        //自定义路径
                        string path = Path.Combine(System.Web.HttpContext.Current.Request.MapPath("upload")+ "\\"+ OID, pathUrls);// System.Web.HttpContext.Current.Server.MapPath("upload") + "\\"+fileName;
                        var pathList = path.Split('u');
                        var PathUrl = "u" + pathList[1];
                        //添加记录到数据库
                        if (isSava < 1)
                        {
                            string sql = @" insert  into PS_SS_AppealNodeEmpAtt([PS_SS_AppealNodeEmpAttOID], [AttachmentName], [FileType], [FilePath], [PS_SS_AppealNodeEmp_FK])
                        values(NEWID(),'" + fileName + "','" + fileType + "','" + PathUrl + "','" + NodeEmpOID + "')";
                            dal.ExecuteQuery(sql);
                        }
                        else
                        {
                            string sql = @" update PS_SS_AppealNodeEmpAtt set AttachmentName='" + fileName + "',FileType='" + fileType + "',FilePath='" + PathUrl + "' where PS_SS_AppealNodeEmp_FK='" + NodeEmpOID + "'";
                            dal.ExecuteQuery(sql);
                        }
                        //上传文件到服务器目录
                        Byte[] bytes = new byte[uploadFile.ContentLength];
                        uploadFile.InputStream.Read(bytes, 0, uploadFile.ContentLength);
                        //判断是否存在这保存目录,没有则创建
                        DirectoryInfo dir = new DirectoryInfo(System.Web.HttpContext.Current.Request.MapPath("upload") + "\\" + OID);
                        if (!dir.Exists)
                        {
                            dir.Create();
                        }
 
                        FileStream fs = new FileStream(path, FileMode.Create);
                        if (uploadFile.ContentLength <= 10 * 1024 * 1024)//文件小于10M时使用同步写方式
                        {
                            fs.Write(bytes, 0, bytes.Length);
                            fs.Flush();
                            fs.Close();
                        }
                        else //文件大于10M时使用异步写方式
                        {
                            fs.BeginWrite(bytes, 0, bytes.Length, BigFileWrite, fs);
                        }
                        meg.message = "上传成功!";
                        context.Response.ContentType = "application/json";
                        context.Response.Write(JsonConvert.SerializeObject(meg));
                        context.Response.End();
                    }
                    catch (Exception ex)
                    {
                        meg.message =ex.Message;
                        context.Response.ContentType = "application/json";
                        context.Response.Write(JsonConvert.SerializeObject(meg));
                        context.Response.End();
                        throw;
                    }
                    //files[0].SaveAs(path);
                }
                else
                {
                    if (fileName != "")
                    {
                        meg.message = "不支持该类型文件,上传失败!";
                        context.Response.ContentType = "application/json";
                        context.Response.Write(JsonConvert.SerializeObject(meg));
                        context.Response.End();
                    }
                }
                #endregion
            }
            if (isV == "2") //下载
            {
                #region 下载
                if (BillNo != "")//判断流水号
                {
                    string sql = @" select AttachmentName,FilePath,FileType from PS_SS_Appeal Appeal 
                    inner join PS_SS_AppealNode Node on Appeal.PS_SS_AppealOID=Node.PS_SS_Appeal_FK
                    inner join PS_SS_AppealNodeEmp Emp on Node.PS_SS_AppealNodeOID=Emp.PS_SS_AppealNode_FK 
                    inner join PS_SS_AppealNodeEmpAtt Att on Emp.PS_SS_AppealNodeEmpOID=Att.PS_SS_AppealNodeEmp_FK
                    where BillNo='" + BillNo + "'";
                    string Jsondata = JsonConvert.SerializeObject(dal.ExecuteQuery(sql));
                    JArray Jsondatas = (JArray)JsonConvert.DeserializeObject(Jsondata);
                    var AttachmentName = "";//文件名
                    var FilePath = "";//文件路径
                    var FileType = "";//文件类型
                    for (int i = 0; i < Jsondatas.Count; i++)
                    {
                        AttachmentName = Jsondatas[i]["AttachmentName"].ToString();
                        FilePath = Jsondatas[i]["FilePath"].ToString();
                        FileType = Jsondatas[i]["FileType"].ToString();
                    }
                    string SavePath = System.Web.HttpContext.Current.Server.MapPath(context.Request.ApplicationPath + "//" + FilePath);
                    FileInfo fileInfo = new FileInfo(SavePath);
                    if (fileInfo.Exists)
                    {
                        var fullPath = SavePath;
                        FileStream fs = new FileStream(fullPath, FileMode.Open);
                        context.Response.Clear();
                        byte[] buffer = new byte[fs.Length];
                        fs.Read(buffer, 0, buffer.Length);
                        context.Response.AppendHeader("Content-type", GetMIMEType(AttachmentName));
                        context.Response.BinaryWrite(buffer);
 
                        context.Response.AppendHeader("Content-Disposition", "attachment;filename=" + FileNameEncode(AttachmentName));
                        fs.Close();
 
                        //FileStream fs = new FileStream(SavePath, FileMode.Open);
                        //context.Response.Clear();
                        //byte[] buffer = new byte[fs.Length];
                        //fs.Read(buffer, 0, buffer.Length);
                        //context.Response.AppendHeader("Content-type", GetMIMEType(AttachmentName));
                        //context.Response.BinaryWrite(buffer);
                        //context.Response.AppendHeader("Content-Disposition", "attachment;filename=" + FileNameEncode(AttachmentName));
                        //fs.Close();
                    }
                    else
                    {
                        meg.message = "file not found!";
                        context.Response.ContentType = "application/json";
                        context.Response.Write(JsonConvert.SerializeObject(meg));
                        context.Response.End();
                    }                
                }
                #endregion
            }
        }
        //文件名URL编码
        private string FileNameEncode(string orign)
        {
            string encoded = HttpUtility.UrlEncode(orign, new System.Text.UTF8Encoding());
            encoded = encoded.Replace("+", "%20");
            return encoded;
        }
        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
        //得到资源MIME类型
        private string GetMIMEType(string fileName)
        {
            string extName = FileNameEncode(fileName);
            if (!String.IsNullOrEmpty(extName))
            {
                return "application/octet-stream";
            }
            string mime = "";
            switch (extName.ToLower())
            {
                case ".png": mime = "image/png"; break;
                case ".bmp": mime = "image/bmp"; break;
                case ".jpeg": mime = "image/jpeg"; break;
                case ".jpg": mime = "image/jpg"; break;
                case ".gif": mime = "image/gif"; break;
                case ".txt": mime = "text/plain"; break;
                default: mime = "application/octet-stream"; break;
            }
            return mime;
        }
        private void BigFileWrite(IAsyncResult ar)
        {
            FileStream fs = (FileStream)ar.AsyncState;
            fs.EndWrite(ar);
            fs.Flush();
            fs.Close();
        }
    }
}

参考文章:http://blog.ncmem.com/wordpress/2023/12/07/net%e6%96%87%e4%bb%b6%e4%b8%8a%e4%bc%a0%e5%92%8c%e4%b8%8b%e8%bd%bd/
欢迎入群一起讨论

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值