Base64檔案上傳服務端開發原始碼
阿新 • • 發佈:2018-12-20
using System; using System.Configuration; using System.IO; using System.Security.Cryptography; using System.Web; namespace Factory { public class FileBase { //檔案在伺服器存放地址 public static readonly string FILE_SRTVICE_PATH = ConfigurationManager.AppSettings["FileService"].ToString(); public static ResultDto<dynamic> UpLoad(UpLoadInfo info) { ResultDto<dynamic> result = new ResultDto<dynamic>(); string filePath = string.Empty; string fileName = string.Empty; string savePath = HttpContext.Current.Server.MapPath("~/"); string folderName = string.Empty; switch (info.fileType) { case (1): folderName ="Images/"; break; case (2): folderName = "Files/"; break; case (3): folderName = "Videos/"; break; default: folderName = "Images/"; break; } savePath += folderName; try { byte[] ibyte = FileConvertUtil.FromBase64ToByte(info.fileByte); MD5 md5 = new MD5CryptoServiceProvider(); byte[] fileKey = md5.ComputeHash(ibyte); string md5Ibyte = Convert.ToBase64String(fileKey); md5Ibyte = md5Ibyte.Replace('/', 'f'); md5Ibyte = md5Ibyte.Replace('@', 'w'); md5Ibyte = md5Ibyte.Replace('+', 'y'); md5Ibyte = md5Ibyte.Replace(' ', 'j'); md5Ibyte = md5Ibyte.Replace('.', 'x'); md5Ibyte = md5Ibyte.Replace('\\', 'd'); md5Ibyte = md5Ibyte.Substring(0, 19); filePath = md5Ibyte.Substring(0, 4) + "/" + md5Ibyte.Substring(4, 3) + "/" + md5Ibyte.Substring(7, 4); fileName = md5Ibyte.Substring(11) + "." + info.extName; string fullName = savePath +"/"+filePath+ "/"; if (!Directory.Exists(fullName)) { Directory.CreateDirectory(fullName); } using (FileStream deflultStream = new System.IO.FileStream(fullName+fileName, FileMode.OpenOrCreate, FileAccess.Write, FileShare.ReadWrite)) { deflultStream.Write(ibyte, 0, ibyte.Length); deflultStream.Close(); } result.Status = 1; result.Message = "上傳成功!!"; result.Data = folderName + filePath+"/"+fileName; } catch(Exception ex) { result.Status = 0; result.Message = "上傳異常!!"; } return result; } } }
ResultDto.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Bandi.Kuube.FileService.Models { public class ResultDtoBase { public ResultDtoBase() { } /// <summary> /// 1.表示成功,其他失敗,自定義 /// </summary> public int Status { get; set; } public string Message { get; set; } } public class ResultDto<T> : ResultDtoBase { public T Data { get; set; } } public class ResultDto<T,V> : ResultDtoBase { public T Data { get; set; } public V Value { get; set; } } }
UpLoadInfo.cs
using System; using System.Collections.Generic; using System.Linq; using System.Web; namespace Bandi.Kuube.FileService.Models { public class UpLoadInfo { public string fileByte { get; set; } /// <summary> /// 字尾名 不需要加點 /// </summary> public string extName { get; set; } /// <summary> /// 1.圖片 2.檔案 /// </summary> public int fileType { get; set; } } }