MVC4.0 WebAPI上传图片重命名以及图文结合
MVC4.0 WebAPI上传后的图片默认以字符串bodypart结合Guid来命名,且没有文件后缀,为解决上传图片重命名以及图文结合发布的问题,在实体对象的处理上,可将图片属性定义为byte[]对象,至于图片的重命名,通过重写继承MultipartFormDataStreamProvider类来解决!
转:https://www.cnblogs.com/ang/archive/2012/10/24/2634176.html
[HttpPost,Route("PostFormFileData")] public async Task<HttpResponseMessage> PostFormFileData() { HttpResponseMessage responseMessage = new HttpResponseMessage(); // Check if the request contains multipart/form-data. // 检查该请求是否含有multipart/form-data if (!Request.Content.IsMimeMultipartContent("form-data")) { throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType); } string root = HttpContext.Current.Server.MapPath("~/App_Data/UploadFile"); if (!Directory.Exists(root)) { Directory.CreateDirectory(root); } try { var provider = new MultipartFormDataStreamProvider(root); //MultipartFormDataContent multipartFormDataContent = new MultipartFormDataContent(); await Request.Content.ReadAsMultipartAsync(provider); var fileInfos = new List<FileInfo>(); // 文件 Dictionary<string, string> dicData = new Dictionary<string, string>(); // 数据 foreach (MultipartFileData fileData in provider.FileData) { var fileHeaders = fileData.Headers; var fileName = fileData.Headers.ContentDisposition.FileName; //获取上传文件实际的文件名 var fileInfo = new FileInfo(fileData.LocalFileName); //获取上传文件在服务上默认的文件名 var fileExt = fileInfo.Extension; if (fileInfo.Length == 0) { //throw new HttpResponseException(HttpRequestMessage.CreateResponse(HttpStatusCode.BadRequest, "不能上传空文件。")); responseMessage = Request.CreateResponse(HttpStatusCode.BadRequest, "不能上传空文件。"); throw new HttpResponseException(HttpStatusCode.BadRequest); } fileInfos.Add(fileInfo); } foreach (var key in provider.FormData.AllKeys) { //接收FormData dicData.Add(key, provider.FormData[key]); } object obj = new { FileData = fileInfos, Data = dicData }; //Newtonsoft.Json.JsonConvert.DeserializeObject //string strContentType = "x-zip-compressed"; //responseMessage.Content = "测试"; //responseMessage.Content.Headers.ContentType = new MediaTypeHeaderValue(string.Format("application/{0}", strContentType)); //responseMessage.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment"); } catch (Exception ex) { //responseMessage = new HttpResponseMessage(HttpStatusCode.NoContent); //responseMessage.Content = new StringContent(ex.Message, Encoding.UTF8); throw; } return responseMessage; }
public class FileUploadController : ApiController { public Task<HttpResponseMessage> PostFile() { HttpRequestMessage request = this.Request; string root = System.Web.HttpContext.Current.Server.MapPath("~/App_Data/uploads"); //var provider = new MultipartFormDataStreamProvider(root);//原写法 var provider = new RenamingMultipartFormDataStreamProvider(root);//重命名写法 //provider.BodyPartFileNames.sel(kv => kv.Value) var task = request.Content.ReadAsMultipartAsync(provider). ContinueWith<HttpResponseMessage>(o => { string file1 = provider.BodyPartFileNames.First().Value;//多张图片循环provider.BodyPartFileNames或provider.FileData //string file1 = provider.GetLocalFileName(provider.FileData[0].Headers);//返回重写的文件名(注意,由于packages包版本的不同,用BodyPartFileNames还是FileData需要留意) // this is the file name on the server where the file was saved return new HttpResponseMessage() { Content = new StringContent("File uploaded." + file1) }; } ); return task; } }
string FileName = item.Headers.ContentDisposition.FileName.Replace("\"", "");
string filePath = Path.Combine(rootPath, FileName);
File.Copy(item.LocalFileName, filePath, true);
https://www.cnblogs.com/CreateMyself/p/6035339.html
再来看看继承MultipartFormDataStreamProvider的类:
public class RenamingMultipartFormDataStreamProvider : MultipartFormDataStreamProvider { public string Root { get; set; } //public Func<FileUpload.PostedFile, string> OnGetLocalFileName { get; set; } public RenamingMultipartFormDataStreamProvider(string root) : base(root) { Root = root; } public override string GetLocalFileName(HttpContentHeaders headers) { string filePath = headers.ContentDisposition.FileName; // Multipart requests with the file name seem to always include quotes. if (filePath.StartsWith(@"""") && filePath.EndsWith(@"""")) filePath = filePath.Substring(1, filePath.Length - 2); var filename = Path.GetFileName(filePath); var extension = Path.GetExtension(filePath); var contentType = headers.ContentType.MediaType; return filename; } }
该方法通过直接指定form的action为请求的WebAPI上传地址来处理;如:
<form name="form1" method="post" enctype="multipart/form-data" action="http://localhost:8000/api/FileUpload/PostFile">。
js
<div> 选择文件:<input type="file" id="file1" /><br /> <input type="button" id="upload" value="上传" /> <img src="wait.gif" style="display:none" id="imgWait" /> </div> <script src="~/Scripts/jquery-1.10.2.js"></script> <script> $(function () { $("#upload").click(function () { $("#imgWait").show(); var formData = new FormData(); formData.append("myfile", document.getElementById("file1").files[0]); formData.append("userId", "123"); formData.append("userName", "测试01"); $.ajax({ url: "/api/file/PostFormFileData", type: "POST", data: formData, /** *必须false才会自动加上正确的Content-Type */ contentType: false, /** * 必须false才会避开jQuery对 formdata 的默认处理 * XMLHttpRequest会对 formdata 进行正确的处理 */ processData: false, success: function (data) { if (data.status == "true") { alert("上传成功!"); } if (data.status == "error") { alert(data.msg); } $("#imgWait").hide(); }, error: function () { alert("上传失败!"); $("#imgWait").hide(); } }); }); }); </script>
另外我们还可以通过向WebAPI提交byte[]形式的文件来解决(以HttpClient方式向WebAPI地址提交上传对象),首先定义文件上传类,以最简单的为例:
相关上传实体类:
/// <summary> /// 文件上传 /// </summary> public class UploadFileEntity { /// <summary> /// 文件名 /// </summary> public string FileName { get; set; } /// <summary> /// 文件二进制数据 /// </summary> public byte[] FileData { get; set; } } /// <summary> /// 文件上传结果信息 /// </summary> public class ResultModel { /// <summary> /// 返回结果 0: 失败,1: 成功。 /// </summary> public int Result { get; set; } /// <summary> /// 操作信息,成功将返回空。 /// </summary> public string Message { get; set; } }
上传的Action方法:
public ActionResult UploadImage() { byte[] bytes = null; using (var binaryReader = new BinaryReader(Request.Files[0].InputStream)) { bytes = binaryReader.ReadBytes(Request.Files[0].ContentLength); } string fileExt = Path.GetExtension(Request.Files[0].FileName).ToLower(); UploadFileEntity entity = new UploadFileEntity(); entity.FileName = DateTime.Now.ToString("yyyyMMddHHmmss") + fileExt;//自定义文件名称,这里以当前时间为例 entity.FileData = bytes; ResultModel rm = HttpClientOperate.Post<ResultModel>("/UploadFile/SaveFile", APIUrl, entity);//封装的POST提交方法,APIUrl为提交地址,大家可还原为HttpClient的PostAsync方式提交 return Content("{\"msg\":\"" + rm.Message + "\"}"); }
WebAPI接收端,主要方法如下(Controller代码略):
public string SaveFile(UploadFileEntity entity) { string retVal = string.Empty; if (entity.FileData != null && entity.FileData.Length > 0) {//由于此例生成的文件含子目录文件等多层,下面处理方法不一定适合大家,保存地址处理大家根据自己需求来 entity.FileName = entity.FileName.ToLower().Replace("\\", "/"); string savaImageName = HttpContext.Current.Server.MapPath(ConfigOperate.GetConfigValue("SaveBasePath")) + entity.FileName;//定义保存地址 string path = savaImageName.Substring(0, savaImageName.LastIndexOf("/")); DirectoryInfo Drr = new DirectoryInfo(path); if (!Drr.Exists) { Drr.Create(); } FileStream fs = new FileStream(savaImageName, FileMode.Create, FileAccess.Write); fs.Write(entity.FileData, 0, entity.FileData.Length); fs.Flush(); fs.Close(); #region 更新数据等其他逻辑 #endregion retVal = ConfigOperate.GetConfigValue("ImageUrl") + entity.FileName; } return retVal;//返回文件地址 }
Httpclient相关扩展方法如下:
UploadFileEntity entity = new UploadFileEntity(); entity.FileName = DateTime.Now.ToString("yyyyMMddHHmmssffff") + fileExt;//自定义文件名称,这里以当前时间为例 entity.FileData = GetByte(Request.Files[0].InputStream); var request = JsonConvert.SerializeObject(entity); HttpContent httpContent = new StringContent(request); httpContent.Headers.ContentType = new MediaTypeHeaderValue("application/json"); var httpClient = new HttpClient(); httpClient.PostAsync("http://localhost:7901/api/FileUpload/SaveFile", httpContent); public static byte[] GetByte(Stream stream) { byte[] fileData = new byte[stream.Length]; stream.Read(fileData, 0, fileData.Length); stream.Close(); return fileData; }
---完成的
using System; using System.Collections.Generic; using System.Drawing; using System.Drawing.Drawing2D; using System.Drawing.Imaging; using System.IO; using System.IO.Compression; using System.Linq; using System.Net; using System.Net.Http; using System.Net.Http.Headers; using System.Text; using System.Threading.Tasks; using System.Web; using System.Web.Http; namespace IDPlat.CommonHelper { /// <summary> /// 文件接收帮助类 /// </summary> public class FileHelper { /// <summary> /// 上传文件 /// </summary> /// <param name="request">http请求信息</param> /// <param name="param">参数</param> /// <param name="option">上传文件限制</param> /// <returns></returns> public static async Task<List<FileUploadResult>> UploadFileAsync(HttpRequestMessage request, UploadFileParam param, FileOption option) { var result = new List<FileUploadResult>(); var files = HttpContext.Current.Request.Files; //var path = AppDomain.CurrentDomain.BaseDirectory; string strVirtualPath = @"/" + param.SavePath.TrimStart('~', '/').TrimEnd('/'); //path = path + strVirtualPath; UserImpersonate userImpersonate = new UserImpersonate(); userImpersonate.ImpersonateWindowsUser(System.Configuration.ConfigurationManager.AppSettings["loginName"], "", System.Configuration.ConfigurationManager.AppSettings["loginPass"]); var path = HttpContext.Current.Server.MapPath(strVirtualPath); if (!Directory.Exists(path)) { Directory.CreateDirectory(path); } try { var streamProvider = new ReNameMultipartFormDataStreamProvider(path); if (!request.Content.IsMimeMultipartContent("form-data")) { throw new HttpResponseException(request.CreateResponse(HttpStatusCode.UnsupportedMediaType)); } await request.Content.ReadAsMultipartAsync(streamProvider); var fileInfos = new List<FileInfo>(); foreach (var fileData in streamProvider.FileData) { var headers = fileData.Headers; var fileInfo = new FileInfo(fileData.LocalFileName); string extension = fileInfo.Extension; if (fileInfo.Length == 0) { throw new HttpResponseException(request.CreateResponse(HttpStatusCode.BadRequest, "不能上传空文件。")); } if (option != null) { // 文件大小是否超出 if (option.LimitSize > 0 && fileInfo.Length > option.LimitSize) { throw new HttpResponseException(request.CreateResponse(HttpStatusCode.BadRequest, string.Format("不能上传超出{0}大小的文件", option.LimitSize))); } // 文件类型是否允许上传 if (option != null && option.Extensions.Length > 0 && !option.Extensions.Contains(fileInfo.Extension.ToLowerInvariant())) { throw new HttpResponseException(request.CreateResponse(HttpStatusCode.BadRequest, string.Format("只能上传{0}文件", string.Join(",", option.Extensions)))); } } fileInfos.Add(fileInfo); } var ImgFileInfos = new List<FileInfo>(); if (param.bCreateThumbnail) { // 筛选出图片类型文件 ImgFileInfos = fileInfos.Where(file => IsImageFile(file.Extension)).ToList(); // 生成缩略图 ImgFileInfos.ForEach(file => { // 缩略图文件名为原图文件名-mi string strMiniFilePath = file.FullName.Insert(file.FullName.LastIndexOf('.'), "-mi"); if (!MakeThumbnailImage(file.FullName, strMiniFilePath, param.iThumWidth, param.iThumHeight)) { // 缩略图生成失败,复制原图作为缩略图 File.Copy(file.FullName, strMiniFilePath, true); } }); } result.AddRange(fileInfos.Except(ImgFileInfos).Select(file => new FileUploadResult { FilePath = strVirtualPath + file.Name })); result.AddRange(ImgFileInfos.Select(file => new FileUploadResult { FilePath = (strVirtualPath + file.Name).Replace("\\", "/"), MiniFilePath = (strVirtualPath + file.Name.Insert(file.Name.LastIndexOf('.'), "-mi")).Replace("\\", "/") })); } catch (Exception ex) { } finally { userImpersonate.UndoImpersonation(); } return result; } /// <summary> /// 上传文件 /// </summary> /// <param name="strSavePath"></param> /// <param name="bCreateThumbnail"></param> /// <param name="strErrorMsg"></param> /// <param name="iThumWidth"></param> /// <param name="iThumHeight"></param> /// <returns></returns> public static List<Dictionary<string, string>> ReceiveFiles(string strSavePath, out string strErrorMsg, bool bCreateThumbnail = false, int iThumWidth = 100, int iThumHeight = 75) { strErrorMsg = ""; List<Dictionary<string, string>> result = new List<Dictionary<string, string>>(); string strVirtualPath = strSavePath; //path = path + strVirtualPath; UserImpersonate userImpersonate = new UserImpersonate(); userImpersonate.ImpersonateWindowsUser(System.Configuration.ConfigurationManager.AppSettings["loginName"], "", System.Configuration.ConfigurationManager.AppSettings["loginPass"]); try { HttpFileCollection files = HttpContext.Current.Request.Files; if (files.Count > 0) { // 物理路径 string strPhysicsPath = HttpContext.Current.Server.MapPath(strVirtualPath); // 目录是否存在,若不存在则创建 if (!Directory.Exists(strPhysicsPath)) { //这里可能需要配置IIS目录权限为可写入。 Directory.CreateDirectory(strPhysicsPath); } strVirtualPath = "/" + strVirtualPath.TrimStart('~', '/').TrimEnd('/') + "/"; strPhysicsPath = strPhysicsPath.TrimEnd('\\') + "\\"; //strDbSavePath = string.Format("/{0}/", strDbSavePath); for (int i = 0; i < files.Count; i++) { HttpPostedFile file = files[i]; //int iMaxLen = HttpHelper.GetMaxRequestLength(); if (file.ContentLength <= 0) { throw new Exception("不能上传空文件。"); } //else if (file.ContentLength > iMaxLen * 1048576) //{ // throw new Exception("不能上传超过" + iMaxLen + "MB的文件。"); //} else { // 扩展名 string strExtendName = Path.GetExtension(file.FileName); strExtendName = string.IsNullOrEmpty(strExtendName) ? ".JPEG" : strExtendName; string strFileName; // 新文件名 if (strExtendName.ToLower().Equals(".png")) { strFileName = Guid.NewGuid().ToString().ToLower() + ".jpg"; } else { strFileName = Guid.NewGuid().ToString().ToLower() + strExtendName; } // 保存文件 file.SaveAs(strPhysicsPath + strFileName); Dictionary<string, string> fileInfo = new Dictionary<string, string>(); fileInfo.Add("name", Path.GetFileName(file.FileName)); fileInfo.Add("path", strVirtualPath + strFileName); // 生成缩略图 if (bCreateThumbnail && IsImageFile(strExtendName)) { // 缩略图文件名为原图文件名-mi string strMiniFileName = strFileName.Insert(strFileName.LastIndexOf('.'), "-mi"); if (!MakeThumbnailImage(strPhysicsPath + strFileName, strPhysicsPath + strMiniFileName, iThumWidth, iThumHeight, true)) { // 缩略图生成失败,复制原图作为缩略图 File.Copy(strPhysicsPath + strFileName, strPhysicsPath + strMiniFileName, true); } fileInfo.Add("minipath", strVirtualPath + strMiniFileName); } result.Add(fileInfo); } } } else { strErrorMsg = "未接收到上传的文件。"; } } catch (Exception ex) { strErrorMsg = ex.Message; } finally { userImpersonate.UndoImpersonation(); } return result; } /// <summary> /// 判断文件是否为图片文件 /// </summary> /// <param name="strExtension">文件扩展名</param> /// <returns></returns> public static bool IsImageFile(string strExtension) { switch (strExtension.ToUpper()) { case ".GIF": case ".JPG": case ".JPEG": case ".BMP": case ".PNG": return true; default: return false; } } #region 生成缩略图 /// <summary> /// 将目录里的图片全部生成缩略图 /// </summary> /// <param name="strImageDir">图片目录物理路径</param> /// <param name="iThumWidth">缩略图宽度</param> /// <param name="iThumHeight">缩略图高度</param> /// <param name="strResult">异常消息</param> /// <param name="bGetFullImage">获取完全的原图(true:获取原图,缩略图按长边取/false:缩略图按短边取,多余的截掉)</param> /// <returns></returns> public static bool BatchMakeThumbnailImage(string strImageDir, int iThumWidth, int iThumHeight, out string strResult, bool bGetFullImage = false) { try { //strImageDir = strImageDir; if (Directory.Exists(strImageDir)) { string[] pathes = Directory.GetFiles(strImageDir); foreach (string strImagePath in pathes) { if (IsImageFile(Path.GetExtension(strImagePath))) { // 缩略图文件名为原图文件名-mi string strThumbImagePath = strImagePath.Insert(strImagePath.LastIndexOf('.'), "-mi"); if (!MakeThumbnailImage(strImagePath, strThumbImagePath, iThumWidth, iThumHeight, bGetFullImage)) { // 缩略图生成失败,复制原图作为缩略图 File.Copy(strImagePath, strThumbImagePath, true); } } } } } catch (Exception ex) { strResult = ex.Message; return false; } strResult = null; return true; } /// <summary> /// 生成缩略图 /// </summary> /// <param name="strOriginalImagePath">源图路径(物理路径)</param> /// <param name="strThumbnailPath">缩略图路径(物理路径)</param> /// <param name="width">缩略图宽度</param> /// <param name="height">缩略图高度</param> /// <param name="bGetFullImage">获取完全的原图(true:获取原图,缩略图按长边取/false:缩略图按短边取,多余的截掉)</param> public static bool MakeThumbnailImage(string strOriginalImagePath, string strThumbnailPath, int width, int height, bool bGetFullImage = false) { Image imgOriginal = Image.FromFile(strOriginalImagePath); return MakeThumbnailImage(imgOriginal, strThumbnailPath, width, height, bGetFullImage); } /// <summary> /// 生成缩略图 /// </summary> /// <param name="imgOriginal">图片对象</param> /// <param name="strThumbnailPath">缩略图路径(物理路径)</param> /// <param name="width">缩略图宽度</param> /// <param name="height">缩略图高度</param> /// <param name="bGetFullImage">获取完全的原图(true:获取原图,缩略图按长边取/false:缩略图按短边取,多余的截掉)</param> /// <returns></returns> private static bool MakeThumbnailImage(Image imgOriginal, string strThumbnailPath, int width, int height, bool bGetFullImage = false) { bool bResult = true; Bitmap bitmap = null; Graphics g = null; try { Rectangle destRect, srcRect; if (bGetFullImage) { Size newSize = NewSize(width, height, imgOriginal.Width, imgOriginal.Height); bitmap = new Bitmap(newSize.Width, newSize.Height); destRect = new Rectangle(0, 0, newSize.Width, newSize.Height); srcRect = new Rectangle(0, 0, imgOriginal.Width, imgOriginal.Height); } else { bitmap = new Bitmap(width, height); destRect = new Rectangle(0, 0, width, height); srcRect = GetSrcRectangle(width, height, imgOriginal.Width, imgOriginal.Height); } g = Graphics.FromImage(bitmap); // 新建一个画板 g.InterpolationMode = InterpolationMode.HighQualityBicubic; g.SmoothingMode = SmoothingMode.HighQuality; // 设置高质量,低速度呈现平滑程度 g.CompositingQuality = CompositingQuality.HighQuality; // 设置画布的描绘质量 g.Clear(Color.Transparent); // 清空画布并以透明背景色填充 // 在指定位置并且按指定大小绘制原图片的指定部分 g.DrawImage(imgOriginal, destRect, srcRect, GraphicsUnit.Pixel); var extension = "jpg"; var extensions = strThumbnailPath.Split('.'); if (extensions.Length > 0) { extension = extensions[extensions.Length - 1]; } //关键质量控制 //获取系统编码类型数组,包含了jpeg,bmp,png,gif,tiff ImageCodecInfo[] icis = ImageCodecInfo.GetImageEncoders(); ImageCodecInfo ici = null; foreach (ImageCodecInfo i in icis) { if (i.MimeType == "image/jpeg" || i.MimeType == "image/bmp" || i.MimeType == "image/png" || i.MimeType == "image/gif") { //根据图片文件名称过滤,作者:陈毓孟 2015-11-09 if (i.FilenameExtension.Contains(extension.ToUpperInvariant())) { ici = i; break; } } } if (ici == null && icis.Length > 0) { ici = icis.FirstOrDefault(i => i.MimeType == "image/jpeg" || i.MimeType == "image/bmp" || i.MimeType == "image/png" || i.MimeType == "image/gif"); } EncoderParameters ep = new EncoderParameters(1); ep.Param[0] = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, (long)100); // 以jpg格式保存缩略图 //bitmap.Save(strThumbnailPath, ImageFormat.Jpeg); bitmap.Save(strThumbnailPath, ici, ep); } catch (Exception ex) { throw new HttpResponseException(HttpStatusCode.BadRequest); } finally { if (imgOriginal != null) { imgOriginal.Dispose(); } if (bitmap != null) { bitmap.Dispose(); } if (g != null) { g.Dispose(); } } return bResult; } /// <summary> /// 返回缩略图尺寸 /// </summary> /// <param name="maxWidth">指定缩略图的宽度</param> /// <param name="maxHeight">指定缩略图的高度</param> /// <param name="width">原始图片的宽度</param> /// <param name="height">原始图片的高度</param> /// <returns></returns> private static Size NewSize(int maxWidth, int maxHeight, int width, int height) { double w = 0.0; double h = 0.0; double sw = Convert.ToDouble(width); double sh = Convert.ToDouble(height); double mw = Convert.ToDouble(maxWidth); double mh = Convert.ToDouble(maxHeight); if (sw < mw && sh < mh) { w = sw; h = sh; } else if ((sw / sh) > (mw / mh)) { w = maxWidth; h = (w * sh) / sw; } else { h = maxHeight; w = (h * sw) / sh; } return new Size(Convert.ToInt32(w), Convert.ToInt32(h)); } /// <summary> /// 生成缩略图时,获取原图指定部分 /// </summary> /// <param name="tw">缩略图宽度</param> /// <param name="th">缩略图高度</param> /// <param name="ow">原图宽度</param> /// <param name="oh">原图高度</param> /// <returns></returns> private static Rectangle GetSrcRectangle(int tw, int th, int ow, int oh) { double x, y, width, height; if (ow * 1.0 / (oh * 1.0) > tw * 1.0 / (th * 1.0)) { width = oh * tw * 1.0 / th; height = oh; x = (ow - width) / 2.0; y = 0; } else { width = ow; height = ow * th * 1.0 / tw; x = 0; y = (oh - height) / 2.0; } return new Rectangle(Convert.ToInt32(x), Convert.ToInt32(y), Convert.ToInt32(width), Convert.ToInt32(height)); } #endregion #region 压缩解压zip文件 /// <summary> /// 压缩Zip文件 /// </summary> /// <param name="files">键值对,key:文件或目录的虚拟路径/value:在zip文件中的目录名,为空则位于zip文件的根目录</param> /// <param name="strZipPath">zip文件虚拟路径</param> /// <returns>返回:是否压缩成功</returns> public static bool CreateZip(Dictionary<string, string> files, string strZipPath) { try { strZipPath = HttpContext.Current.Server.MapPath(strZipPath); string strZipDir = strZipPath.Substring(0, strZipPath.LastIndexOf('\\')); if (!Directory.Exists(strZipDir)) { Directory.CreateDirectory(strZipDir); } if (File.Exists(strZipPath)) { File.Delete(strZipPath); } // 使用 CreateEntryFromFile 方法添加文件 // 使用 ZipFile 的静态方法创建压缩文件 using (ZipArchive zipArchive = ZipFile.Open(strZipPath, ZipArchiveMode.Create)) { List<string> fileNames = new List<string>(); foreach (KeyValuePair<string, string> file in files) { string strFilePath = HttpContext.Current.Server.MapPath(file.Key); string strFileName = strFilePath.Trim('\\').Split('\\').Reverse().First<string>(); if (file.Key != "" && !fileNames.Contains(strFileName)) { fileNames.Add(strFileName); zipArchive.CreateEntryFromFile(strFilePath, file.Value == "" ? strFileName : file.Value + "/" + strFileName); } } } } catch (Exception ex) { return false; } return true; } /// <summary> /// 压缩文件夹成Zip文件 /// </summary> /// <param name="files">键值对,key:文件或目录的虚拟路径/value:在zip文件中的目录名,为空则位于zip文件的根目录</param> /// <param name="strDirectoryPath">要压缩的文件夹虚拟路径</param> /// <param name="strZipPath">zip文件虚拟路径</param> /// <param name="strSaveFileDirPath">保存文件的文件夹路径</param> /// <param name="isOpen">是否开启用户进程模拟</param> /// <returns>返回:是否压缩成功</returns> public static bool CreateZipFromDirectory(Dictionary<string, string> files, string strSaveFileDirPath, string strZipPath, string strDirectoryPath, bool isOpen = true) { strSaveFileDirPath = HttpContext.Current.Server.MapPath(strSaveFileDirPath); strZipPath = HttpContext.Current.Server.MapPath(strZipPath); strDirectoryPath = HttpContext.Current.Server.MapPath(strDirectoryPath); UserImpersonate userImpersonate = null; try { string strZipDir = strZipPath.Substring(0, strZipPath.LastIndexOf('\\')); if (File.Exists(strZipPath)) { File.Delete(strZipPath); } if (!Directory.Exists(strSaveFileDirPath)) { Directory.CreateDirectory(strSaveFileDirPath); } if (!Directory.Exists(strZipDir)) { Directory.CreateDirectory(strZipDir); } if (isOpen) { userImpersonate = new UserImpersonate(); userImpersonate.ImpersonateWindowsUser(System.Configuration.ConfigurationManager.AppSettings["loginName"], "", System.Configuration.ConfigurationManager.AppSettings["loginPass"]); } foreach (KeyValuePair<string, string> file in files) { string strFilePath = HttpContext.Current.Server.MapPath(file.Key); string strFileName = strFilePath.Trim('\\').Split('\\').Reverse().First<string>(); File.Copy(strFilePath, string.Format("{0}/{1}", strSaveFileDirPath, strFileName)); } // 压缩文件夹 ZipFile.CreateFromDirectory(strDirectoryPath, strZipPath); } catch (Exception ex) { throw ex; //Directory.Delete(strDirectoryPath); //return false; } finally { if (isOpen && userImpersonate!= null) { userImpersonate.UndoImpersonation(); } } return true; } /// <summary> /// 解压Zip文件 /// </summary> /// <param name="strZipPath">zip文件虚拟路径</param> /// <param name="strZipDir">解压目录虚拟路径</param> /// <param name="strResult">异常消息</param> /// <returns></returns> public static bool ExtractZip(string strZipPath, string strZipDir, out string strResult) { try { //strZipPath = HttpContext.Current.Server.MapPath(strZipPath); //strZipDir = HttpContext.Current.Server.MapPath(strZipDir); ZipFile.ExtractToDirectory(strZipPath, strZipDir); } catch (Exception ex) { strResult = ex.Message; return false; } finally { } strResult = null; return true; } /// <summary> /// 下载文件(输出文件流) /// </summary> /// <param name="strFilePath">文件路径</param> /// <param name="strContentType">文件扩展名</param> /// <returns></returns> public static HttpResponse DownloadFile(string strFilePath, string strContentType) { FileStream fs = null; HttpResponse response = HttpContext.Current.Response; try { var strFileTitle = Path.GetFileName(strFilePath); strFileTitle = HttpUtility.UrlEncode(strFileTitle.Trim(), Encoding.UTF8); //清空输出流 response.Clear(); response.Buffer = true; //定义输出文件编码及类型和文件名 response.ContentEncoding = Encoding.UTF8; response.AppendHeader("Content-Disposition", "attachment;filename=" + strFileTitle); response.ContentType = string.Format("application/{0};charset=UTF-8", strContentType); //每次读取的长度 const long ChunkSize = 10000; byte[] buffer = new byte[ChunkSize]; fs = new FileStream(strFilePath, FileMode.Open, FileAccess.Read, FileShare.Read); long dataLengthToRead = fs.Length; //分段读取,避免占用过多内存 while (dataLengthToRead > 0 && response.IsClientConnected) { int lengthRead = fs.Read(buffer, 0, Convert.ToInt32(ChunkSize)); response.OutputStream.Write(buffer, 0, lengthRead); response.Flush(); dataLengthToRead = dataLengthToRead - lengthRead; } } catch (Exception) { response.StatusCode = 204; response.StatusDescription = "文件下载失败。"; } finally { fs.Flush(); fs.Close(); response.End(); //File.Delete(strFilePath); } return response; } /// <summary> /// 下载文件(输出文件流) /// </summary> /// <param name="strFilePath">文件路径</param> /// <param name="strContentType">文件扩展名</param> /// <returns></returns> public static HttpResponseMessage DownloadFileStream(string strFilePath, string strContentType) { HttpResponseMessage httpResponseMessage = new HttpResponseMessage(HttpStatusCode.OK); FileStream fileStream = null; try { if (!File.Exists(strFilePath)) { httpResponseMessage = new HttpResponseMessage(HttpStatusCode.NoContent); } fileStream = File.OpenRead(strFilePath); httpResponseMessage.Content = new StreamContent(fileStream); httpResponseMessage.Content.Headers.ContentType = new MediaTypeHeaderValue(string.Format("application/{0}", strContentType)); httpResponseMessage.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment") { FileName = Path.GetFileName(strFilePath) }; } catch (Exception ex) { if (fileStream != null) { fileStream.Close(); fileStream.Flush(); } httpResponseMessage = new HttpResponseMessage(HttpStatusCode.NoContent); httpResponseMessage.Content = new StringContent(ex.Message, Encoding.UTF8); } return httpResponseMessage; } #endregion /// <summary> /// 读取文本文件 /// </summary> /// <param name="strTxtPath">文本文件路径(物理路径)</param> /// <returns></returns> public static string ReadTextFile(string strTxtPath) { if (!File.Exists(strTxtPath)) { return ""; } string strData = File.ReadAllText(strTxtPath); return strData; } /// <summary> /// 将图片文件或目录的图片文件移入到新位置 /// </summary> /// <param name="strSourcePath">要移动的图片文件或目录的物理路径</param> /// <param name="strTargetPath">新位置的虚拟路径,如果strSourcePath是一个文件,则strTargetPath必须是一个文件名</param> /// <param name="lstFileName">存储文件名称的集合</param> public static void MoveImageFile(string strSourcePath, string strTargetPath, List<string> lstFileName) { UserImpersonate UserImpersonate = new UserImpersonate(); UserImpersonate.ImpersonateWindowsUser(System.Configuration.ConfigurationManager.AppSettings["loginName"], "", System.Configuration.ConfigurationManager.AppSettings["loginPass"]); try { strTargetPath = HttpContext.Current.Server.MapPath(strTargetPath); if (!Directory.Exists(strTargetPath)) { Directory.CreateDirectory(strTargetPath); } if (Directory.Exists(strSourcePath) || File.Exists(strSourcePath)) { //string strTargetDir = Path.GetDirectoryName(strTargetPath); if (Directory.Exists(strSourcePath)) { var folder = new DirectoryInfo(strSourcePath); folder.GetFiles().Where(p => IsImageFile(p.Extension)).ToList().ForEach(p => { lstFileName.Add(p.Name); File.Move(p.FullName, Path.Combine(strTargetPath, p.Name)); }); } else { lstFileName.Add(strSourcePath); File.Move(strSourcePath, Path.Combine(strTargetPath, Path.GetFileName(strSourcePath))); } } } catch { throw; } finally { UserImpersonate.UndoImpersonation(); } } } }
/// <summary> /// 重命名上传的文件名 /// </summary> public class ReNameMultipartFormDataStreamProvider : MultipartFormDataStreamProvider { /// <summary> /// /// </summary> /// <param name="rootPath"></param> public ReNameMultipartFormDataStreamProvider(string rootPath) : base(rootPath) { } /// <summary> /// 获取文件名 /// </summary> /// <param name="headers"></param> /// <returns></returns> public override string GetLocalFileName(HttpContentHeaders headers) { string exp = Path.GetExtension(headers.ContentDisposition.FileName.TrimStart('"').TrimEnd('"')); // 截取扩展名 string name = base.GetLocalFileName(headers); return name + exp; } }

浙公网安备 33010602011771号