简单粗暴,直接上代码吧
//这是提交post的
public String GetImageStr(String imgFilePath)
{ //图片路径 string path = @"E:\MyProject\CommonHelp\WebApiDemo\img\1.jpg"; FileInfo file = new FileInfo(path); var stream = file.OpenRead(); byte[] buffer = new byte[file.Length]; //读取图片字节流 stream.Read(buffer, 0, Convert.ToInt32(file.Length)); //将base64字符串保存到base64.txt文件中 StreamWriter sw = new StreamWriter(@"E:\MyProject\CommonHelp\WebApiDemo\img\base64.txt", false, Encoding.UTF8); //将字节流转化成base64字符串 string base64=Convert.ToBase64String(buffer);var request = (HttpWebRequest)WebRequest.Create("http://localhost:2349/api/UserApi/UploadHead");
var postData = "UserInfoId=94"; postData += "&Base64="+base64; postData += "&SuffixType=jpg"; var data = Encoding.ASCII.GetBytes(postData);request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded"; request.ContentLength = data.Length;using (var streams = request.GetRequestStream())
{ streams.Write(data, 0, data.Length); }var response = (HttpWebResponse)request.GetResponse();
var responseString = new StreamReader(response.GetResponseStream()).ReadToEnd();
return responseString.ToString(); }
//这是接口提供方
public ImageDto UploadImage(UploadImageDto uploadImageDto)
{ uploadImageDto.Base64 = uploadImageDto.Base64.Replace(' ', '+'); string path = string.Format("/UploadImge/" + DateTime.Now.ToString("yyyyMMdd") + "/"); byte[] imgByte = Convert.FromBase64String(uploadImageDto.Base64); MemoryStream ms = new MemoryStream(imgByte); Image image = System.Drawing.Image.FromStream(ms); string fileName = string.Format("{0}." + uploadImageDto.SuffixType, DateTime.Now.ToString("yyyyMMddhhmmssffff") + RandomHelper.GenerateCheckCodeNum(6)); string filePath = string.Format("{0}{1}", path, fileName); string serverPath = HttpContext.Current.Server.MapPath("~" + path); if (!Directory.Exists(serverPath)) { Directory.CreateDirectory(serverPath); } //保存图片 image.Save(serverPath + fileName); string ImageUrl = WebConfigHelper.GetAppSettingsInfo("ImageUrl"); int ImgInfoId = _baseImgInfoService.Insert(new BaseImgInfoEntity { CreateTime = DateTime.Now, Path = filePath, Title = "接口图片上传", Type = 0, Source = ImageUrl }); return new ImageDto { ImageId = ImgInfoId, Source = ImageUrl, Path = filePath, Title = "接口图片上传" }; }
//注意!!!!这里必须把‘ ’空格替换成‘+’加号,具体情况未明
uploadImageDto.Base64 = uploadImageDto.Base64.Replace(' ', '+');
转换成Base64之后进行UrlEncode编码即可
string text = System.Web.HttpUtility.UrlEncode("heart", System.Text.Encoding.UTF8); //UrlEncode编码
string data = System.Web.HttpUtility.UrlDecode(text, System.Text.Encoding.UTF8); //UrlDecode解码