base64字符串转文件,以及ngImgCrop裁剪图片并上传保存到服务器示例

base64字符串是包含文件格式的文件字符串,例如:data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAMgAAADICAYAAACtWK6eAAAgAElEQVR4Xsy9+……

根据base64字符串可以转化成真实的文件。思路是,首先将base64字符串读取城字节数组;然后将字节数组读入到字节流(内存流);其次将base64字符串开头部分包含的文件格式提取出来,得到文件类型并转换成相应后缀名;最后,根据字节流和文件类型,即可转化成相应的文件,并保存到物理磁盘。

 

特别是最近玩AngularJS时候,用到图片上传,裁剪图片保存功能,需要用到ngImgCrop裁剪图片控件。它就是将图片裁剪后保存成base64字符串结果的。

 

示例:base64编码的文本转为图片

/// <summary>
/// base64编码的文本转为图片
/// </summary>
/// <param name="base64"></param>
/// <returns></returns>
private static Image Base64StringToImage(string base64)
{
  byte[] bytes = Convert.FromBase64String(base64);
  using (MemoryStream ms = new MemoryStream(bytes))
  {
    Bitmap bmp = new Bitmap(ms);
    return bmp;
  }
}

 

示例:获取base64字符串开头部分包含的文件格式

var m = new Regex(@"(?<=data\:)[\w\/_\.]+(?=\;)", RegexOptions.IgnoreCase).Match(byteStr);
string ContentType = null != m ? m.Value : "image/png";

 

示例:获取文件大小

/// <summary>
/// 获取文件/文件夹大小(字节)
/// </summary>
/// <param name="filePath">路径</param>
/// <returns></returns>
private static long FileSize(string filePath)
{
  long temp = 0;

  //路径是否是文件
  if (File.Exists(filePath) == false)
  {

    //文件目录
    string[] entries = Directory.GetFileSystemEntries(filePath);
    foreach (string item in entries)
    {

      //遍历文件目录内的所有子文件目录,子文件
      temp += FileSize(item);
    }
  }
  else
  {
    FileInfo fileInfo = new FileInfo(filePath);
    return fileInfo.Length; //获取真实文件的大小(字节)
  }
  return temp;
}

 

全部代码:

 1 public class FileUploadResultModel
 2 {
 3     public Guid FileID { get; set; }
 4     public long FileSize { get; set; }
 5 }
 6 
 7 
 8 public static class Base64FileHandle
 9 {
10     /// <summary>
11     /// base64编码的文本转为图片
12     /// </summary>
13     /// <param name="base64"></param>
14     /// <returns></returns>
15     private static Image Base64StringToImage(string base64)
16     {
17         byte[] bytes = Convert.FromBase64String(base64);
18         using (MemoryStream ms = new MemoryStream(bytes))
19         {
20             Bitmap bmp = new Bitmap(ms);
21             return bmp;
22         }
23     }
24     /// <summary>
25     /// 获取文件/文件夹大小(字节)
26     /// </summary>
27     /// <param name="filePath">路径</param>
28     /// <returns></returns>
29     private static long FileSize(string filePath)
30     {
31         long temp = 0;
32         if (File.Exists(filePath) == false)
33         {
34             string[] entries = Directory.GetFileSystemEntries(filePath);
35             foreach (string item in entries)
36             {
37                 temp += FileSize(item);
38             }
39         }
40         else
41         {
42             FileInfo fileInfo = new FileInfo(filePath);
43             return fileInfo.Length;
44         }
45         return temp;
46     }
47     private static string SuffixName(string ContentType)
48     {
49         switch (ContentType.Trim().ToLower())
50         {
51             case "image/jpg":
52             case "image/jpeg":
53                 return ".jpg";
54 
55             case "image/gif":
56                 return ".gif";
57             case "image/bmp":
58                 return ".bmp";
59             case "image/png":
60                 return ".png";
61             default:
62                 return "";
63         }
64     }
65 
66     /// <summary>
67     /// 创建圈子
68     /// </summary>
69     /// <param name="community"></param>
70     /// <returns></returns>
71     public static ResponseModel<FileUploadResultModel> ngImgCropHandle(string base64)
72     {
73         var response = new ResponseModel<FileUploadResultModel>() { IsLogin = true };
74 
75         string byteStr = base64.Trim();//data:image/png;base64,       
76         int delLength = byteStr.IndexOf(',') + 1;
77         string str = byteStr.Substring(delLength, byteStr.Length - delLength);
78         Image returnImage = Base64StringToImage(str);
79 
80         var m = new Regex(@"(?<=data\:)[\w\/_\.]+(?=\;)", RegexOptions.IgnoreCase).Match(byteStr);
81         string ContentType = null != m ? m.Value : "image/png";
82 
83         Guid filename = Guid.NewGuid();
84         string filepath = @"D:\wwwroot\" + filename + SuffixName(ContentType);
85         returnImage.Save(filepath);
86 
87         response.Data = new FileUploadResultModel() { FileID = filename, FileSize = FileSize(filepath) };
88         response.Success = true;
89         response.Message = "ok";
90         return response;
91     }
92 
93 
94 }

 

posted @ 2017-04-19 11:42 熊仔其人 阅读(...) 评论(...) 编辑 收藏