/// <summary> /// 通过文件流上传文件方法 /// </summary> /// <param name="byteData">文件字节数组</param> /// <param name="fileName">文件名</param> /// <param name="isThumbnail">是否生成缩略图</param> /// <param name="isWater">是否打水印</param> /// <returns>上传成功返回JSON字符串</returns> 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("{\"status\": 0, \"msg\": \"请选择要上传的文件!\"}"); } //检查文件扩展名是否合法 if (!CheckFileExt(fileExt)) { return("{\"status\": 0, \"msg\": \"不允许上传" + fileExt + "类型的文件!\"}"); } //检查文件大小是否合法 if (!CheckFileSize(fileExt, byteData.Length)) { return("{\"status\": 0, \"msg\": \"文件超过限制的大小!\"}"); } //如果是图片,检查图片是否超出最大尺寸,是则裁剪 if (IsImage(fileExt) && (this.sysConfig.imgmaxheight > 0 || this.sysConfig.imgmaxwidth > 0)) { byteData = Thumbnail.MakeThumbnailImage(byteData, fileExt, this.sysConfig.imgmaxwidth, this.sysConfig.imgmaxheight); } //如果是图片,检查是否需要生成缩略图,是则生成 if (IsImage(fileExt) && isThumbnail && this.sysConfig.thumbnailwidth > 0 && this.sysConfig.thumbnailheight > 0) { thumbData = Thumbnail.MakeThumbnailImage(byteData, fileExt, this.sysConfig.thumbnailwidth, this.sysConfig.thumbnailheight, this.sysConfig.thumbnailmode); } else { newThumbnailPath = newFilePath; //不生成缩略图则返回原图 } //如果是图片,检查是否需要打水印 if (IsWaterMark(fileExt) && isWater) { switch (this.sysConfig.watermarktype) { case 1: byteData = WaterMark.AddImageSignText(byteData, fileExt, this.sysConfig.watermarktext, this.sysConfig.watermarkposition, this.sysConfig.watermarkimgquality, this.sysConfig.watermarkfont, this.sysConfig.watermarkfontsize); break; case 2: byteData = WaterMark.AddImageSignPic(byteData, fileExt, this.sysConfig.watermarkpic, this.sysConfig.watermarkposition, this.sysConfig.watermarkimgquality, this.sysConfig.watermarktransparency); break; } } //检查本地上传的物理路径是否存在,不存在则创建 if (!Directory.Exists(fullUpLoadPath)) { Directory.CreateDirectory(fullUpLoadPath); } //保存主文件 FileHelp.SaveFile(byteData, fullUpLoadPath + newFileName); //保存缩略图文件 if (thumbData != null) { FileHelp.SaveFile(thumbData, fullUpLoadPath + newThumbnailFileName); } //处理完毕,返回JOSN格式的文件信息 return("{\"status\": 1, \"msg\": \"上传文件成功!\", \"name\": \"" + fileName + "\", \"path\": \"" + newFilePath + "\", \"thumb\": \"" + newThumbnailPath + "\", \"size\": " + byteData.Length + ", \"ext\": \"" + fileExt + "\"}"); } catch { return("{\"status\": 0, \"msg\": \"上传过程中发生意外错误!\"}"); } }