using System; using System.Collections.Generic; using System.Drawing; using System.IO; using System.Linq; using System.Net; using System.Net.Http; using System.Runtime.Serialization.Formatters.Binary; using System.Web; using System.Web.Http; namespace WebApi.Controllers { public class HomeController : ApiController { /// <summary> /// 接收Base64编码格式的图片 /// </summary> public void Upload() { //获取base64编码的图片 HttpContextBase context = (HttpContextBase)Request.Properties["MS_HttpContext"]; string text = context.Request.Form["file"]; //获取文件储存路径 string path = context.Request.MapPath("~/"); //获取当前项目所在目录 string datetime = GetTimeStamp(); string suffix = ".jpg"; //文件的后缀名根据实际情况 string strPath = path + "App_Data/" + datetime + suffix; //获取图片并保存 Base64ToImg(text.Split(‘,‘)[1]).Save(strPath); } //解析base64编码获取图片 private Bitmap Base64ToImg(string base64Code) { MemoryStream stream = new MemoryStream(Convert.FromBase64String(base64Code)); return new Bitmap(stream); } //获取当前时间段额时间戳 public string GetTimeStamp() { TimeSpan ts = DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, 0); return Convert.ToInt64(ts.TotalMilliseconds).ToString(); } } }
时间: 2024-10-24 01:48:49