C#底层库–记录日志帮助类
本文链接:https://blog.csdn.net/youcheng_ge/article/details/124187709
C#底层库–数据库访问帮助类(MySQL版)
本文链接:https://blog.csdn.net/youcheng_ge/article/details/126886379
C#底层库–获取文件版本和MD5值
本文链接:https://blog.csdn.net/youcheng_ge/article/details/112513871
C#底层库–操作文件帮助类FileHelper(获取目录的所有文件)
本文链接:https://blog.csdn.net/youcheng_ge/article/details/126887161
C#底层库–操作Excel帮助类(读取、导出表格)
本文链接:https://blog.csdn.net/youcheng_ge/article/details/126887445
C#底层库–软件版本管理XML
本文链接:https://blog.csdn.net/youcheng_ge/article/details/110195766
C#底层库–随机数生成类
本文链接:https://blog.csdn.net/youcheng_ge/article/details/126888812
C#底层库–正则表达式帮助类
本文链接:https://blog.csdn.net/youcheng_ge/article/details/109745286
C#底层库–CSV和DataTable相互转换
本文链接:https://blog.csdn.net/youcheng_ge/article/details/128804367
C#底层库–Image图片操作类
本文链接:https://blog.csdn.net/youcheng_ge/article/details/128805298
C#底层库–JSON序列化、反序列化扩展类
本文链接:https://blog.csdn.net/youcheng_ge/article/details/128805705
C#底层库–cookie操作辅助类
本文链接:https://blog.csdn.net/youcheng_ge/article/details/128816347
C#底层库–数据实体类
本文链接:https://blog.csdn.net/youcheng_ge/article/details/128816638
C#底层库–Image图片操作类
本文链接:https://blog.csdn.net/youcheng_ge/article/details/128805298
本专栏为【底层库】,将介绍研发过程中 通用的函数。我们将这些固化的源码,进行重写、规范封装、单元测试、集成测试,从而形成通用化模块库,本专栏称为“底层库”。
作为研发人员的你,并不需要花大量时间,完全掌握“底层库”的含义,你只需要几行调用代码,就可以解决一些项目上碰到的难题。大家有任何问题,可以评论区反馈,私信我。
底层库已实现功能:数据库操作、加解密算法、日志记录、HTTP通信、Socket通信、API前后端交互、邮件发送、文件操作、配置参数存储、Excel导入导出、CSV和DataTable转换、压缩解压、自动编号、Session操作等,
UpLoad文件上传下载辅助类。包含:通过文件流上传文件方法、裁剪图片并保存、保存远程文件到本地、删除上传文件
创建类UpLoad.cs,复制以下代码。
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
namespace yimi.Common
{
public class UpLoad
{
// private SysConfig sysConfig;
public UpLoad()
{
// sysConfig= XmlModelHelper.Load();
// sysConfig = new BLL.sysconfig().loadConfig();
}
///
/// 通过文件流上传文件方法
///
/// 文件字节数组
/// 文件名
/// 是否生成缩略图
/// 是否打水印
/// 上传成功返回JSON字符串
public string FileSaveAs(byte[] byteData, string fileName, bool isThumbnail, bool isWater)
{
try
{
string fileExt = Path.GetExtension(fileName).Trim('.'); //文件扩展名,不含“.”
string newFileName = Utils.GetRamCode() + "." + fileExt; //随机生成新的文件名
string newThumbnailFileName = "thumb_" + newFileName; //随机生成缩略图文件名
string upLoadPath = GetUpLoadPath(); //本地上传目录相对路径
string fullUpLoadPath = Utils.GetMapPath(upLoadPath); //本地上传目录的物理路径
string newFilePath = upLoadPath + newFileName; //本地上传后的路径
string newThumbnailPath = upLoadPath + newThumbnailFileName; //本地上传后的缩略图路径
byte[] thumbData = null; //缩略图文件流
//检查文件字节数组是否为NULL
if (byteData == null)
{
return "{\"code\": 500, \"msg\": \"请选择要上传的文件!\"}";
}
//检查文件扩展名是否合法
if (!CheckFileExt(fileExt))
{
return "{\"code\": 500, \"msg\": \"不允许上传" + fileExt + "类型的文件!\"}";
}
//检查文件大小是否合法
if (!CheckFileSize(fileExt, byteData.Length))
{
return "{\"code\": 500, \"msg\": \"文件超过限制的大小!\"}";
}
//如果是图片,检查图片是否超出最大尺寸,是则裁剪
if (IsImage(fileExt) && (SysConfig.Intance.imgmaxheight > 0 || SysConfig.Intance.imgmaxwidth > 0))
{
byteData = Thumbnail.MakeThumbnailImage(byteData, fileExt, SysConfig.Intance.imgmaxwidth, SysConfig.Intance.imgmaxheight);
}
//如果是图片,检查是否需要生成缩略图,是则生成
if (IsImage(fileExt) && isThumbnail && SysConfig.Intance.thumbnailwidth > 0 && SysConfig.Intance.thumbnailheight > 0)
{
thumbData = Thumbnail.MakeThumbnailImage(byteData, fileExt, SysConfig.Intance.thumbnailwidth, SysConfig.Intance.thumbnailheight, SysConfig.Intance.thumbnailmode);
}
else
{
newThumbnailPath = newFilePath; //不生成缩略图则返回原图
}
//如果是图片,检查是否需要打水印
if (IsWaterMark(fileExt) && isWater)
{
switch (SysConfig.Intance.watermarktype)
{
case 1:
byteData = WaterMark.AddImageSignText(byteData, fileExt, SysConfig.Intance.watermarktext, SysConfig.Intance.watermarkposition,
SysConfig.Intance.watermarkimgquality, SysConfig.Intance.watermarkfont, SysConfig.Intance.watermarkfontsize);
break;
case 2:
byteData = WaterMark.AddImageSignPic(byteData, fileExt, SysConfig.Intance.watermarkpic, SysConfig.Intance.watermarkposition,
SysConfig.Intance.watermarkimgquality, SysConfig.Intance.watermarktransparency);
break;
}
}
//检查本地上传的物理路径是否存在,不存在则创建
if (!Directory.Exists(fullUpLoadPath))
{
Directory.CreateDirectory(fullUpLoadPath);
}
//保存主文件
FileHelper.SaveFile(byteData, fullUpLoadPath + newFileName);
//保存缩略图文件
if (thumbData != null)
{
FileHelper.SaveFile(thumbData, fullUpLoadPath + newThumbnailFileName);
}
//处理完毕,返回JOSN格式的文件信息
return "{\"code\": 0, \"msg\": \"上传文件成功!\", \"name\": \""
+ fileName + "\", \"path\": \"" + newFilePath + "\", \"thumb\": \""
+ newThumbnailPath + "\", \"size\": " + byteData.Length + ", \"ext\": \"" + fileExt + "\"}";
}
catch (Exception e)
{
// LogHelper.error(e);
return "{\"code\": 500, \"msg\": \"上传过程中发生意外错误!\"}";
}
}
///
/// 裁剪图片并保存
///
public string CropSaveAs(string fileUri, int maxWidth, int maxHeight, int cropWidth, int cropHeight, int X, int Y)
{
string fileExt = Path.GetExtension(fileUri).Trim('.'); //文件扩展名,不含“.”
if (string.IsNullOrEmpty(fileExt) || !IsImage(fileExt))
{
return "{\"code\": 500, \"msg\": \"该文件不是图片!\"}";
}
byte[] byteData = null;
//判断是否远程文件
if (fileUri.ToLower().StartsWith("http://") || fileUri.ToLower().StartsWith("https://"))
{
WebClient client = new WebClient();
byteData = client.DownloadData(fileUri);
client.Dispose();
}
else //本地源文件
{
string fullName = Utils.GetMapPath(fileUri);
if (File.Exists(fullName))
{
FileStream fs = File.OpenRead(fullName);
BinaryReader br = new BinaryReader(fs);
br.BaseStream.Seek(0, SeekOrigin.Begin);
byteData = br.ReadBytes((int)br.BaseStream.Length);
fs.Close();
}
}
//裁剪后得到文件流
byteData = Thumbnail.MakeThumbnailImage(byteData, fileExt, maxWidth, maxHeight, cropWidth, cropHeight, X, Y);
//删除原图
DeleteFile(fileUri);
//保存制作好的缩略图
return FileSaveAs(byteData, fileUri, false, false);
}
///
/// 保存远程文件到本地
///
/// URI地址
/// 上传后的路径
public string RemoteSaveAs(string sourceUri)
{
if (!IsExternalIPAddress(sourceUri))
{
return "{\"code\"50: 0, \"msg\": \"INVALID_URL\"}";
}
if (sourceUri.ToLower().IndexOf("aspx") > 0 || sourceUri.ToLower().IndexOf("asp") > 0 || sourceUri.ToLower().IndexOf("ashx") > 0)
return "{\"code\": 500, \"msg\": \"抓取错误:不是图片资源\"}";
if (sourceUri.ToLower().IndexOf("jpg") < 0 && sourceUri.ToLower().IndexOf("png") < 0 && sourceUri.ToLower().IndexOf("bmp") < 0 && sourceUri.ToLower().IndexOf("jpeg") < 0)
return "{\"code\": 500, \"msg\": \"抓取错误:不是图片资源\"}";
var request = HttpWebRequest.Create(sourceUri) as HttpWebRequest;
using (var response = request.GetResponse() as HttpWebResponse)
{
if (response.StatusCode != HttpStatusCode.OK)
{
return "{\"code\": 500, \"msg\": \"Url returns " + response.StatusCode + ", " + response.StatusDescription + "\"}";
}
if (response.ContentType.IndexOf("image") == -1)
{
return "{\"code\": 500, \"msg\": \"Url is not an image\"}";
}
try
{
byte[] byteData = FileHelper.ConvertStreamToByteBuffer(response.GetResponseStream());
return FileSaveAs(byteData, sourceUri, false, false);
}
catch (Exception e)
{
return "{\"code\": 500, \"msg\": \"抓取错误:" + e.Message + "\"}";
}
}
}
///
/// 删除上传文件
///
/// 相对地址或网址
public void DeleteFile(string fileUri)
{
//文件不应是上传文件,防止跨目录删除
if (fileUri.IndexOf("..") == -1 && fileUri.ToLower().StartsWith(SysConfig.Intance.webpath.ToLower() + SysConfig.Intance.filepath.ToLower()))
{
FileHelper.DeleteUpFile(fileUri);
}
}
#region 私有方法
///
/// 返回上传目录相对路径
///
/// 上传文件名
private string GetUpLoadPath()
{
string path = SysConfig.Intance.webpath + SysConfig.Intance.filepath + "/"; //站点目录+上传目录
switch (SysConfig.Intance.filesave)
{
case 1: //按年月日每天一个文件夹
path += DateTime.Now.ToString("yyyyMMdd");
break;
default: //按年月/日存入不同的文件夹
path += DateTime.Now.ToString("yyyyMM") + "/" + DateTime.Now.ToString("dd");
break;
}
return path + "/";
}
///
/// 是否需要打水印
///
/// 文件扩展名,不含“.”
private bool IsWaterMark(string _fileExt)
{
//判断是否开启水印
if (SysConfig.Intance.watermarktype > 0)
{
//判断是否可以打水印的图片类型
ArrayList al = new ArrayList();
al.Add("bmp");
al.Add("jpeg");
al.Add("jpg");
al.Add("png");
if (al.Contains(_fileExt.ToLower()))
{
return true;
}
}
return false;
}
///
/// 是否为图片文件
///
/// 文件扩展名,不含“.”
private bool IsImage(string _fileExt)
{
ArrayList al = new ArrayList();
al.Add("bmp");
al.Add("jpeg");
al.Add("jpg");
al.Add("gif");
al.Add("png");
if (al.Contains(_fileExt.ToLower()))
{
return true;
}
return false;
}
///
/// 检查是否为合法的上传文件
///
private bool CheckFileExt(string _fileExt)
{
//检查危险文件
string[] excExt = { "asp", "aspx", "ashx", "asa", "asmx", "asax", "php", "jsp", "htm", "html" };
for (int i = 0; i < excExt.Length; i++)
{
if (excExt[i].ToLower() == _fileExt.ToLower())
{
return false;
}
}
//检查合法文件
string[] allowExt = (SysConfig.Intance.fileextension + "," + SysConfig.Intance.videoextension).Split(',');
for (int i = 0; i < allowExt.Length; i++)
{
if (allowExt[i].ToLower() == _fileExt.ToLower())
{
return true;
}
}
return false;
}
///
/// 检查文件大小是否合法
///
/// 文件扩展名,不含“.”
/// 文件大小(B)
private bool CheckFileSize(string _fileExt, int _fileSize)
{
//将视频扩展名转换成ArrayList
ArrayList lsVideoExt = new ArrayList(SysConfig.Intance.videoextension.ToLower().Split(','));
//判断是否为图片文件
if (IsImage(_fileExt))
{
if (SysConfig.Intance.imgsize > 0 && _fileSize > SysConfig.Intance.imgsize * 1024)
{
return false;
}
}
else if (lsVideoExt.Contains(_fileExt.ToLower()))
{
if (SysConfig.Intance.videosize > 0 && _fileSize > SysConfig.Intance.videosize * 1024)
{
return false;
}
}
else
{
if (SysConfig.Intance.attachsize > 0 && _fileSize > SysConfig.Intance.attachsize * 1024)
{
return false;
}
}
return true;
}
///
/// 检查文件地址是否文件服务器地址
///
/// 文件地址
private bool IsExternalIPAddress(string url)
{
var uri = new Uri(url);
switch (uri.HostNameType)
{
case UriHostNameType.Dns:
var ipHostEntry = Dns.GetHostEntry(uri.DnsSafeHost);
foreach (IPAddress ipAddress in ipHostEntry.AddressList)
{
byte[] ipBytes = ipAddress.GetAddressBytes();
if (ipAddress.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork)
{
if (!IsPrivateIP(ipAddress))
{
return true;
}
}
}
break;
case UriHostNameType.IPv4:
return !IsPrivateIP(IPAddress.Parse(uri.DnsSafeHost));
}
return false;
}
///
/// 检查IP地址是否本地服务器地址
///
/// IP地址
private bool IsPrivateIP(IPAddress myIPAddress)
{
if (IPAddress.IsLoopback(myIPAddress)) return true;
if (myIPAddress.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork)
{
byte[] ipBytes = myIPAddress.GetAddressBytes();
// 10.0.0.0/24
if (ipBytes[0] == 10)
{
return true;
}
// 172.16.0.0/16
else if (ipBytes[0] == 172 && ipBytes[1] == 16)
{
return true;
}
// 192.168.0.0/16
else if (ipBytes[0] == 192 && ipBytes[1] == 168)
{
return true;
}
// 169.254.0.0/16
else if (ipBytes[0] == 169 && ipBytes[1] == 254)
{
return true;
}
}
return false;
}
#endregion
}
}
我放在了窗体页面,新增一个按钮,点击按钮时触发。
///
/// 上传文件 单个文件 不支持多文件
///
///
///
public ContentResult upload(HttpPostedFileBase files)
{
if (files != null)
{
bool _iswater = false; //默认不打水印
bool _isthumbnail = false; //默认不生成缩略图
if (DNTRequest.GetQueryString("IsWater") == "1")
{
_iswater = true;
}
if (DNTRequest.GetQueryString("IsThumbnail") == "1")
{
_isthumbnail = true;
}
byte[] byteData = FileHelper.ConvertStreamToByteBuffer(files.InputStream);
if (byteData.Length >= 0)
{
//context.Response.Write("{\"status\": 0, \"msg\": \"请选择要上传文件!\"}");
//return;
UpLoad upLoad = new UpLoad();
string msg = upLoad.FileSaveAs(byteData, files.FileName, _isthumbnail, _iswater);
return Content(msg, "application/json; charset=utf-8");
}
return JsonError("上传失败");
}
return JsonError("未找到文件");
}