C#——⽂件上传(⼀般处理程序ashx)Framework版本:.Net Framework 4
1、FileInfo实体
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using MongoDB.Bson;
using ReligionServer.util;
stant;
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();
}
getsavefilenamepublic 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, 0);
if (CommonUtil.ForeignKey()))
{
NoParams<Model.FileInfo>(context, "关联外键为空, 还请检测关联属性是否上传成功, 外键是否为空");
}
else if (base.TypeCode()))
{
fileInfo.setTypeCode("0");
NoParams<Model.FileInfo>(context, "TypeCode is null or  '' ...");
}
else
{
List<Model.FileInfo> uploadFileList = FileInsert(context, InitFileInfo(context, 0));
if (uploadFileList.Count == 0)
{
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, 1);
if (base.TypeCode()))
{
fileInfo.setTypeCode("0");
NoParams<Model.FileInfo>(context, "TypeCode is null or  '' ...");
}
else {
List<Model.FileInfo> uploadFileList = FileInsert(context, fileInfo);
if (uploadFileList.Count == 0)
{
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, 0);
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 > 0)
{
HttpPostedFile item = null;
for (int i = 0; i < fileCollection.Count; i++)
{
item = fileCollection[i];
String suffix = item.FileName.Split('.')[item.FileName.Split('.').Length - 1];//获取⽂件的后缀名
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.TypeCode() + ":" + "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.TypeCode() + ":" + "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.Base64S if (fileInfoList.Count > 0)
{
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)
{
//暂时不做
}

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。