首页 > 其他分享 >.Net文件上传和下载

.Net文件上传和下载

时间:2023-12-07 10:14:57浏览次数:34  
标签:PS string SS context var Net 上传 Response 下载

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/

欢迎入群一起讨论

 

 

标签:PS,string,SS,context,var,Net,上传,Response,下载
From: https://www.cnblogs.com/songsu/p/17881055.html

相关文章

  • python多线程下载图片
    urls.json文件数据格式如下["https://example.com/image1.jpg","https://example.com/image2.jpg","https://example.com/image3.jpg"] 代码如下importjsonimportrequestsimportthreadingdefdownload_image(url):respo......
  • .NET 6 (C#) Microsoft.Extensions.Logging 日志框架的使用
    .NET6中的日志框架主要是基于Microsoft.Extensions.Logging,这是一个通用的、可扩展的日志记录接口,允许使用不同的日志提供程序(例如控制台、文件、第三方库等)进行日志记录。本文主要介绍.NET6(C#)中Microsoft.Extensions.Logging日志框架的使用,以及相关的示例代码。1......
  • .NET 6 (C#) Serilog 日志框架的使用
    ​Serilog是.NET6中常用的日志框架之一,用于记录和管理应用程序的日志信息。它具有灵活的配置选项和丰富的扩展功能,使开发人员能够轻松地集成日志记录功能到他们的应用程序中。Serilog是一个用于.NET应用程序的诊断日志库。它易于设置,具有清晰的API,并且可以在所有最新的.NET平台上......
  • 数据中心的操作系统——kubernets
    操作系统的功能和模块与Kubernetes的功能和模块做了一个对比:Kubernetes作为数据中心的操作系统还是主要管理数据中心里面的四种硬件资源:CPU、内存、存储、网络。对于CPU和内存这两种计算资源的管理,我们可以通过Docker技术完成。它可以将CPU和内存资源,通过namespace和cg......
  • 并发设计类分析(Guava/Netty)
    1.限流器1.1限流器常见限流算法:计数器算法计数器算法是一种简单的限流方法,通过对请求进行计数,当请求达到一定的阈值时,进行限制。这种方法适用于简单场景,但不够灵活。容易出现临界时间点限流失效问题。滑动窗口算法滑动窗口算法维护一个时间窗口内的请求数量,通过动态调......
  • skywalking 部署安装 https://blog.csdn.net/swg321321/article/details/129704345
    https://blog.csdn.net/swg321321/article/details/129704345 前言在分布式系统中会出现服务间的相互调用,且服务数量众多。一般会出现如下异常请求出现异常,需要定位定位具体是哪个服务器发生异常,需要对这个请求链路一步一步调试才能确定那个服务出现异常。出现定位异常服务难......
  • PHP+JS实现大文件切片上传功能实现实例源码
    近期公司的项目中,涉及到上传大文件的问题,大文件上传用普通表单上传时出现的问题是,无法断点续存,一但中途中断上传,就要重头开始,这很明显不是我们想要的,所以经过一番查询,学习了一下大文件分割上传的方法。并且使用简单的php做服务端处理程序实现一个功能demo,供以后回顾使用。本人也是......
  • Vue前端+后端实现带进度条文件分片上传
    传输参数对象packagecom.deju.provider.upload.domain;importlombok.Data;importorg.springframework.web.multipart.MultipartFile;@DatapublicclassMultipartFileParam{ //文件传输任务ID privateStringtaskId; //当前为第几分片 privateintchun......
  • SENetV2: 用于通道和全局表示的聚合稠密层
    SENetV2:Aggregateddenselayerforchannelwiseandglobalrepresentations 官方代码是用tf.keras实现(论文中没有标注):https://github.com/mahendran-narayanan/SENetV2-Aggregated-dense-layer-for-channelwise-and-global-representations我用torch和tf实现了一下:htt......
  • 「GIS数据」下载全国的GeoJSON、shp格式数据(精确到乡镇街道级)-2023年12月更新
    发现个可以免费下载全国 geojson 数据的网站,推荐一下。支持全国、省级、市级、区/县级、街道/乡镇级以及各级的联动数据,支持导入矢量地图渲染框架中使用,例如:D3、Echarts等geojson数据下载地址:https://geojson.hxkj.vip该项目github地址:https://github.com/TangSY/echarts-m......