记录一个简单webapi 上传图片
2021-06-05 02:03
标签:data event ber name returns 客户 简单的 test post 图片转base64字符串,到接口后,再转回保存.代码里面是转成byte[]之后转的,也可以用base64字符串直接转图片. 只想记录一下简单的流程。 1,服务端 保存图片业务代码: 记录一个简单webapi 上传图片 标签:data event ber name returns 客户 简单的 test post 原文地址:https://www.cnblogs.com/siyunsanqu/p/10832325.html
{
public string UpLoad(string fileName,string filePath,byte[] fileData)
{
Bitmap map =BitmapFromBytes(fileData);
filePath = System.Web.Hosting.HostingEnvironment.MapPath(@"~/") +"images\\" + fileName;
map.Save(filePath, ImageFormat.Jpeg);
return filePath;
}
/// byte[]数组转换为Bitmap
///
/// byte[]数组
///
public static Bitmap BitmapFromBytes(byte[] bytes)
{
Bitmap bitmap = null;
try
{
using (MemoryStream stream = new MemoryStream(bytes))
{
bitmap = new Bitmap((Image)new Bitmap(stream));
}
}
catch { }
}
}
{
[HttpPost]
public string UpLoadFile(dynamic fileInfo)
{
string fileName = fileInfo.fileName;
string filePath = string.Empty;
string fileData1 = fileInfo.fileData;
byte[] fileData = Convert.FromBase64String(fileData1);
BLL.UpLoadFile upLoad = new BLL.UpLoadFile();
}
[HttpPost]
public string Test()
{
return "123";
}
}
{
//创建一个处理序列化的DataContractJsonSerializer
DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(FileInfo));
MemoryStream ms = new MemoryStream();
FileInfo fileInfo = new FileInfo()
{
fileName = "123.jpeg",
fileData =Convert.ToBase64String( GetImage())
};
//将资料写入MemoryStream
serializer.WriteObject(ms, fileInfo);
//一定要在这设定Position
ms.Position = 0;
HttpContent content = new StreamContent(ms);//将MemoryStream转成HttpContent
content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/json");
HttpClient client = new HttpClient();
HttpResponseMessage response = client.PostAsync("http://localhost:803/api/UpLoad/UpLoadFile" , content).Result;
if (response.IsSuccessStatusCode)
{
string ret = response.Content.ReadAsStringAsync().Result;
string json = JsonConvert.DeserializeObject(ret).ToString();
MessageBox.Show("成功 :"+json);
}
}
public class FileInfo
{
[DataMember]
public string fileName
{
get;
set;
}
[DataMember]
public string fileData
{
get;
set;
}
}
上一篇:C#-NPOI操作EXCEL
下一篇:win10无法安装软件解决