Framework版本:.Net Framework 4

1、FileInfo实体

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using MongoDB.Bson;
using ReligionServer.util;
using ReligionServer.constant; namespace ReligionServer.Model
{
//为什么会有多余的get set方法,因为测试写的,没有删
//封装的一个文件类, 文件基本信息
public class FileInfo
{ public ObjectId _id; public String FileCode { get; set; }//目前还没有研究出ObjectId序列化的最好解决方式, 所以暂时使用FileCode替代Id
public String Name { get; set; }
public String Type { get; set; }
public String Desc { get; set; }
public String Path { get; set; }
public int Access { get; set; }
public String ForeignKey { get; set; }
public DateTime CreateTime { get; set; }
public String TypeCode { get; set; }//辅助字段 public FileInfo() { } public void set_Id(ObjectId id)
{
this._id = id;
} public ObjectId get_Id()
{
return this._id;
} public void setFileCode()
{
this.FileCode = CommonUtil.CreateId();
} public String getFileCode()
{
return this.FileCode;
} public void setName(String name)
{
this.Name = name;
} public String getName()
{
return this.Name;
} public void setType(String type)
{
this.Type = FileTypeConstant.GetType(type);
} public String getType()
{
return this.Type;
} public void setDesc(String desc)
{
this.Desc = desc;
} public String getDesc()
{
return this.Desc;
} public void setPath(String path)
{
this.Path = path;
} public String getPath()
{
return this.Path;
} public void setAccess(int access)
{
this.Access = access;
} public int getAccess()
{
return this.Access;
} public void setForeignKey()
{
this.ForeignKey = CommonUtil.CreateId();
} public String getForeignKey()
{
return this.ForeignKey;
} public void setCreateTime()
{
this.CreateTime = DateTime.Now;
} public DateTime getCreateTime()
{
return this.CreateTime; } public void setTypeCode(String code)
{
this.TypeCode = code;
} public String getTypeCode()
{
return this.TypeCode;
} }
}

2、Handler具体实现

using System;

using System.IO;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using ReligionServer.util;
using ReligionServer.Model;
using ReligionServer.service;
using System.Text.RegularExpressions; namespace ReligionServer.handler
{
/// <summary>
/// FileHandler 的摘要说明
/// 处理文件请求
/// </summary>
public class FileHandler : BaseHandler, IHttpHandler
{ private FileInfoService fileInfoService = new FileInfoService();
private readonly String targetSavePath = "~/ReligionFile/"; public void ProcessRequest(HttpContext context)
{
base.InitAction(context);
}
#region 文件上传
//和第三方表关联的文件上传初始化逻辑
public void Upload_Foreign(HttpContext context)
{
Model.FileInfo fileInfo = InitFileInfo(context, );
if (CommonUtil.IsEmpty(fileInfo.getForeignKey()))
{
NoParams<Model.FileInfo>(context, "关联外键为空, 还请检测关联属性是否上传成功, 外键是否为空");
}
else if (base.IsEmpty(fileInfo.getTypeCode()))
{
fileInfo.setTypeCode("");
NoParams<Model.FileInfo>(context, "TypeCode is null or '' ...");
}
else
{
List<Model.FileInfo> uploadFileList = FileInsert(context, InitFileInfo(context, ));
if (uploadFileList.Count == )
{
Error<String>(context, new List<String>() { "上传失败: 后台获取文件信息失败" });
}
else
{
int errorCount = (int)context.Items["FileUploadErrorCount"];
int successCount = uploadFileList.Count - errorCount;
Success<String>(context, new List<String>() { "一共上传 " + uploadFileList.Count + "个文件,其中成功 " + successCount + "个,失败" + errorCount + "个" });
}
} } //文件上传初始化逻辑
public void Upload(HttpContext context)
{
Model.FileInfo fileInfo = InitFileInfo(context, );
if (base.IsEmpty(fileInfo.getTypeCode()))
{
fileInfo.setTypeCode("");
NoParams<Model.FileInfo>(context, "TypeCode is null or '' ...");
}
else {
List<Model.FileInfo> uploadFileList = FileInsert(context, fileInfo);
if (uploadFileList.Count == )
{
Error<String>(context, new List<String>() { "上传失败: 后台获取文件信息失败" });
}
else
{
int errorCount = (int)context.Items["FileUploadErrorCount"];
int successCount = uploadFileList.Count - errorCount;
Success<String>(context, new List<String>() { "一共上传 " + uploadFileList.Count + "个文件,其中成功 " + successCount + "个,失败" + errorCount + "个" });
}
}
} /// <summary>
/// 供类相互调用的文件上传
/// </summary>
/// <param name="context"></param>
/// <param name="foreignKey"></param>
/// <returns></returns>
public List<Model.FileInfo> Upload_Invoke(HttpContext context, String foreignKey) {
if (!base.IsEmpty(foreignKey)) {
Model.FileInfo fileInfo = InitFileInfo(context, );
fileInfo.ForeignKey = foreignKey;
List<Model.FileInfo> uploadFileList = FileInsert(context, fileInfo);
return uploadFileList;
}
return new List<Model.FileInfo>();
} //执行文件转存以及数据库记录插入的方法
private List<Model.FileInfo> FileInsert(HttpContext context, Model.FileInfo fileInfo)
{
List<Model.FileInfo> fileInfoList = new List<Model.FileInfo>(); //List<Model.FileInfo> fileInfoList = new List<Model.FileInfo>();
String directoryName = DateUtil.CurrentDateTimeValue();//文件夹名称
//HttpContext.Current.Request.PhysicalApplicationPath 获取当前正在执行的服务器应用程序的根目录的物理文件系统路径
String targetPhysicalFilePath = HttpContext.Current.Request.PhysicalApplicationPath + "ReligionFile/" + directoryName;
//不存在就创建
if (!Directory.Exists(targetPhysicalFilePath))
{
Directory.CreateDirectory(targetPhysicalFilePath);
} //获取上传文件集合
HttpFileCollection fileCollection = context.Request.Files;
//HttpPostedFile temp = context.Request.Files["regfile"];//测试
//String tempe = context.Request.Params["regfile"];
//HttpPostedFileWrapper fileWrapper = context.Request.Files[0]; Model.FileInfo tempFileInfo = null;
if (fileCollection.Count > )
{
HttpPostedFile item = null;
for (int i = ; i < fileCollection.Count; i++)
{
item = fileCollection[i];
String suffix = item.FileName.Split('.')[item.FileName.Split('.').Length - ];//获取文件的后缀名
tempFileInfo = new Model.FileInfo();
tempFileInfo = (Model.FileInfo)BeanUtil.PropCopy(fileInfo, tempFileInfo);
//tempFileInfo.set_Id(CommonUtil.CreateObjectId());这样设置Id是无效的
tempFileInfo.setName(item.FileName);//存的是以前的文件名, 是否有意义
tempFileInfo.setFileCode();
tempFileInfo.setType(suffix);
tempFileInfo.setCreateTime();
suffix = "." + suffix;
if (suffix.ToLower().Equals(".txt"))
{
suffix = ".doc";//这里是否有必要? 这是个问题
}
String realFileName = Guid.NewGuid().ToString() + suffix;
tempFileInfo.setTypeCode(tempFileInfo.getTypeCode() + ":" + "ReligionFile/" + directoryName + "/" + realFileName);
tempFileInfo.setPath("ReligionFile/" + directoryName + "/" + realFileName);
item.SaveAs(context.Server.MapPath(targetSavePath + directoryName + "/" + realFileName));//文件转存 必须是文件的根目录, 而且不能使虚拟目录
fileInfoList.Add(tempFileInfo);
}
//foreach (String key in fileCollection) {
//这里前台只有一个文件选择框, 那么多文件时keys都是相同的,
// HttpPostedFile item = fileCollection[key];
// String suffix = item.FileName.Split('.')[item.FileName.Split('.').Length - 1];//获取文件的后缀名
// fileInfo.setName(item.FileName);
// fileInfo.setFileCode();
// fileInfo.setType(suffix);
// fileInfo.setCreateTime();
// suffix = "." + suffix;
// if (suffix.ToLower().Equals(".txt")) {
// suffix = ".doc";//这里是否有必要? 这是个问题
// }
// String realFileName = Guid.NewGuid().ToString() + suffix;
// fileInfo.setTypeCode(fileInfo.getTypeCode() + ":" + "ReligionFile/" + directoryName + realFileName);
// item.SaveAs(context.Server.MapPath(targetSavePath + directoryName + "/" + realFileName));//文件转存 必须是文件的根目录, 而且不能使虚拟目录
// fileInfoList.Add(fileInfo);
//}
int errorCount = fileInfoService.InsertBatchFileInfo(fileInfoList);//文件信息批量入表, 返回失败个数
context.Items.Add("FileUploadErrorCount", errorCount); } return fileInfoList; } /// <summary>
/// Base64格式的图片上传
/// </summary>
/// <param name="context"></param>
public void Insert_Base64_Img(HttpContext context)
{
vo.Base64Image base64Image = base.GetInstance<vo.Base64Image>(context, new vo.Base64Image());
if (base.IsEmpty(base64Image.Base64String))
{
NoParams<vo.Base64Image>(context, "上传参数存在空值");
}
else
{
List<Model.FileInfo> fileInfoList = util.ImageUtil.Base64ImageInsertBatch(context, util.ArrraysUtil.PurifyArrays<String>(Regex.Split(base64Image.Base64String, "c#", RegexOptions.IgnoreCase)));
if (fileInfoList.Count > )
{
int errorCount = fileInfoService.InsertBatchFileInfo(fileInfoList);
int successCount = fileInfoList.Count - errorCount;
Success<String>(context, new List<String>() { "一共上传 " + fileInfoList.Count + "个文件,其中成功 " + successCount + "个,失败" + errorCount + "个" });
}
else
{
Error<String>(context, new List<String>() { "上传失败: 后台将Base64转存时失败" });
}
}
} #endregion #region 文件删除 /// <summary>
/// 根据ObjectId删除指定的文件信息
/// </summary>
/// <param name="context"></param>
public void Del_ObjectId(HttpContext context)
{
//暂时不做
} /// <summary>
/// 根据FileCode删除指定的文件信息
/// </summary>
/// <param name="context"></param>
public void Del_FileCode(HttpContext context)
{
Model.FileInfo fileInfo = this.InitFileInfo(context, -);
fileInfo = fileInfoService.FindFileInfoByFileCode(fileInfo.getFileCode());
if (fileInfo != null)
{
if (fileInfoService.RemoveFileInfoByFileCode(fileInfo.getFileCode()))
{
RemoveLocalFile(fileInfo);
Success<Model.FileInfo>(context, new List<Model.FileInfo>() { fileInfo });
}
else
{
Error<Model.FileInfo>(context, new List<Model.FileInfo>() { fileInfo });
}
}
else
{
NoParams<Model.FileInfo>(context, "该条记录不存在,无法删除");
}
} /// <summary>
/// 根据外键ForeignKey删除所关联的文件信息
/// </summary>
/// <param name="context"></param>
public void Del_ForeignKey(HttpContext context)
{ } /// <summary>
/// 根据传递进来的FileInfo的path字段删除服务器上对应的文件
/// </summary>
/// <param name="fileInfo"></param>
private void RemoveLocalFile(Model.FileInfo fileInfo)
{
System.Diagnostics.Debug.WriteLine(HttpContext.Current.Request.PhysicalApplicationPath + fileInfo.getPath());
//FileUtil.RemoveFile(context.Request.PhysicalApplicationPath + fileInfo.getPath());
FileUtil.RemoveFile(HttpContext.Current.Request.PhysicalApplicationPath + fileInfo.getPath());
} #endregion #region 文件修改 /// <summary>
/// 根据FileCode修改指定的文件信息
/// </summary>
/// <param name="context"></param>
public void Update_FileCode(HttpContext context)
{
Model.FileInfo target = InitFileInfo(context, -);
String fileCode = target.getFileCode();
List<Model.FileInfo> list = null;
if (CommonUtil.IsEmpty(target.getForeignKey()) || CommonUtil.IsEmpty(target.getFileCode()))
{
NoParams<Model.FileInfo>(context, "关联外键ForeignKey或FileCode为空");
}
else
{
list = FileInsert(context, InitFileInfo(context, ));
}
if (null != list)
{
target = list[];
target.FileCode = fileCode;
Model.FileInfo source = fileInfoService.FindFileInfoByFileCode(target.getFileCode());
if (null != source)
{
target._id = source._id;
target.Access = source.Access;
target.ForeignKey = source.ForeignKey;
if (fileInfoService.UpdateAllByFileCode(target))
{
RemoveLocalFile(source);//如果上传成功, 就将原来的文件删除
Success<Model.FileInfo>(context, new List<Model.FileInfo>() { fileInfoService.FindFileInfoByFileCode(target.FileCode) });
}
else
{
Error<Model.FileInfo>(context, new List<Model.FileInfo>() { target });
RemoveLocalFile(target);//如果更新失败, 就将上传的文件删除
}
}
else
{
Init<Model.FileInfo>(context, "", "", new List<Model.FileInfo>() { });
}
}
} #endregion #region 文件查找 /// <summary>
/// 根据FileCode查找指定的文件信息
/// </summary>
/// <param name="context"></param>
public void Query_FileCode(HttpContext context)
{
Model.FileInfo fileInfo = fileInfoService.FindFileInfoByFileCode(this.InitFileInfo(context, -).FileCode);
if (fileInfo == null)
{
NoParams<Model.FileInfo>(context, "该记录不存在");
}
else
{
Success<Model.FileInfo>(context, new List<Model.FileInfo>() { fileInfo });
}
} /// <summary>
/// 根据ForeignKey查询所有的文件信息
/// </summary>
/// <param name="context"></param>
public void Query_Foreign(HttpContext context)
{
//Model.FileInfo info = this.InitFileInfo(context, -1);
List<Model.FileInfo> list = fileInfoService.FindFileInfoListByForeignKey(this.InitFileInfo(context, -).ForeignKey);
//if (list == null || list.Count == 0) {
// NoParams<Model.FileInfo>(context, "没有匹配的记录");
//} else {
// Success<Model.FileInfo>(context, list);
//}
Success<Model.FileInfo>(context, list);
} #endregion
//初始化FileInfo
private Model.FileInfo InitFileInfo(HttpContext context, int access)
{
Model.FileInfo fileInfo = ParametersUtil.GetInstanceFormRequest<Model.FileInfo>(context, new Model.FileInfo());//这里主要是获取ForeignKey if (access != -)
{
fileInfo.setAccess(access);//设置文件资源类型 {0表示关联; 1表示独立资源,没有关联} -1表示不作处理
}
return fileInfo;
} public bool IsReusable
{
get
{
return false;
}
}
}
}

C#——文件上传(一般处理程序ashx)的更多相关文章

  1. Asp.Net实现无刷新文件上传并显示进度条(非服务器控件实现)(转)

    Asp.Net实现无刷新文件上传并显示进度条(非服务器控件实现) 相信通过Asp.Net的服务器控件上传文件在简单不过了,通过AjaxToolkit控件实现上传进度也不是什么难事,为什么还要自己辛辛苦 ...

  2. Asp.Net 无刷新文件上传并显示进度条的实现方法及思路

    相信通过Asp.Net的服务器控件上传文件在简单不过了,通过AjaxToolkit控件实现上传进度也不是什么难事,为什么还要自己辛辛苦苦来 实现呢?我并不否认”拿来主义“,只是我个人更喜欢凡是求个所以 ...

  3. 强大的支持多文件上传的jQuery文件上传插件Uploadify

    支持多文件上传的jQuery文件上传插件Uploadify,目前此插件有两种版本即Flash版本和HTML5版本,对于HTML5版本会比较好的支持手机浏览器,避免苹果手机Safari浏览器不支持Fla ...

  4. jQuery文件上传插件Uploadify(转)

    一款基于flash的文件上传,有进度条和支持大文件上传,且可以多文件上传队列. 这款在flash的基础上增加了html5的支持,所以在移动端也可以使用. 由于官方提供的版本是flash免费,html5 ...

  5. 聊一聊jquery文件上传(支持多文件上传)

    谈到文件上传,现在一般都用现成的组件可以使用.PC端的可以使用uploadify.针对微网站H5也有uploadifive.但是这组件并不能满足各种场景的需求,例如:预览 切图 放大缩小,取消之类的. ...

  6. 基于uploadify.js实现多文件上传和上传进度条的显示

    uploadify是JQuery的一个插件,主要实现文件的异步上传功能,可以自定义文件大小限制.文件类型.是否自动上传等属性,可以显示上传的进度条.官网地址是http://www.uploadify. ...

  7. [Asp.net]通过uploadify将文件上传到B服务器的共享文件夹中

    写在前面 客户有这样的一个需求,针对项目中文档共享的模块,客户提出如果用户上传特别的大,或者时间久了硬盘空间就会吃满,能不能将这些文件上传到其他的服务器?然后就稍微研究了下这方面的东西,上传到网络中的 ...

  8. AjaxUpLoad.js使用实现文件上传

    AjaxUpLoad.js的使用实现无刷新文件上传,如图. 图1 文件上传前 图2 文件上传后 1.创建页面并编写HTML [html] view plaincopy   上传文档: <div  ...

  9. 文件上传利器JQuery上传插件Uploadify

    在做日常项目中,经常在后台需要上传图片等资源文件,之前使用过几次这个组件,感觉非常好用 ,但是每次使用的时候都是需要经过一番查阅,所以还不如记住在这里,以后使用的时候就翻翻. 他的官方网站如下:htt ...

随机推荐

  1. C++11新特性之九——function、bind以及lamda表达式总结

    本文是C++0x系列的第四篇,主要是内容是C++0x中新增的lambda表达式, function对象和bind机制.之所以把这三块放在一起讲,是因为这三块之间有着非常密切的关系,通过对比学习,加深对 ...

  2. cocos2d-x游戏引擎核心之十——网络通信

    一.建立基本的http通信并得到返回信息 1.创建cocos2dx工程 2.项目引用外部库 如果要使用cocos2dx的CCHttpClient来进行网络访问,则需要引入cocos2dx的相关库,详细 ...

  3. oracle 字段自增 两段代码搞定

    (这几天做了个小小课程设计时用的是oracle数据库,第一次用,发现oracle和我们以前用的sql server .mysql是有如此多不同的地方,下面是遇到的问题之一和解决方法,和大家分享下) 用 ...

  4. MQTT协议笔记之mqtt.io项目TCP协议支持

    前言 MQTT定义了物联网传输协议,其标准倾向于原始TCP实现.构建于TCP的上层协议堆栈,诸如HTTP等,在空间上多了一些处理路径,稍微耗费了CPU和内存,虽看似微乎其微,但对很多处理能力不足的嵌入 ...

  5. DNS、链接网页、资源预加载处理

    从网页性能的角度来看,DNS的解析时间是比较耗时的.因此如果能预先下载网页中用到的其它域的资源.可提前进行DNS解析: <link rel="dns-prefetch" hr ...

  6. 心脏滴血HeartBleed漏洞研究及其POC

    一.漏洞原理: 首先声明,我虽然能看懂C和C++的每一行代码,但是他们连在一起我就不知道什么鬼东西了.所以关于代码说理的部分只能参考其他大牛的博客了. /* 据说源码中有下面两条语句,反正我也没看过源 ...

  7. 3.node的url属性

    node的url属性 1.parse: [Function: urlParse],2.format: [Function: urlFormat],3.resolve: [Function: urlRe ...

  8. 【BZOJ3935】Rbtree 树形DP

    [BZOJ3935]Rbtree Description 给定一颗 N 个点的树,树上的每个点或者是红色,或者是黑色. 每个单位时间内,你可以任选两个点,交换它们的颜色. 出于某种恶趣味,你希望用最少 ...

  9. Linux系列-Xshell连接本地VMware安装的Linux虚拟机

    一.安装VMwareWorkstation并安装RedHat虚拟机,这里安装步骤省略,网络的资料很多,大侠们不如百度或者谷歌一下,大把的资料. 二.打开本地电脑的“网络连接”,你会发现多出了2个网络适 ...

  10. Oracle在linux下命令行无法使用退格键退格,无法使用上下键切换历史命令的解决办法

    使用xshell等客户端登录oracl时在命令行无法使用退格键也无法使用上下键切换历史命令可以使用rlwrap解决 1,linux环境 2,下载rlwrap wget http://files.cnb ...