C# c将图像从WPF发送到WebAPI
我有一个WebAPI 2.1服务ASP.NETMVC4,用于接收和镜像以及相关数据。 我需要从WPF应用程序发送此图像,但我得到404未找到错误 服务器端 客户端 url存在,我需要将其编码为json格式,但我不知道如何编码C# c将图像从WPF发送到WebAPI,c#,wpf,asp.net-web-api,C#,Wpf,Asp.net Web Api,我有一个WebAPI 2.1服务ASP.NETMVC4,用于接收和镜像以及相关数据。 我需要从WPF应用程序发送此图像,但我得到404未找到错误 服务器端 客户端 url存在,我需要将其编码为json格式,但我不知道如何编码 谢谢你的时间 您案例中的方法参数以QueryString形式接收 我建议您将参数列表转换为一个对象,如下所示: public class PhotoUploadRequest { public string id; public string tr;
谢谢你的时间 您案例中的方法参数以QueryString形式接收 我建议您将参数列表转换为一个对象,如下所示:
public class PhotoUploadRequest
{
public string id;
public string tr;
public string image;
}
然后在API中将字符串从Base64String转换为buffer,如下所示:
var buffer = Convert.FromBase64String(request.image);
然后将其强制转换为HttpPostedFileBase
现在您有了图像文件。你想干什么就干什么
完整代码如下:
编辑:
我忘了为MemoryPostedFile类添加代码
检查是否已确保启用属性路由?我还建议使用DTO模型来管理数据谢谢@Ramy,它可以工作@Rammohamed嗨,函数第二行的MemoryPostedFile是什么。我在MSDN中找不到任何东西。@MilindThakkar再次检查答案,我更新了它。@RamyMohamed:谢谢,我会尝试更新它。
public class PhotoUploadRequest
{
public string id;
public string tr;
public string image;
}
var buffer = Convert.FromBase64String(request.image);
HttpPostedFileBase objFile = (HttpPostedFileBase)new MemoryPostedFile(buffer);
[HttpPost]
[Route("api/StoreImage")]
public string StoreImage(PhotoUploadRequest request)
{
var buffer = Convert.FromBase64String(request.image);
HttpPostedFileBase objFile = (HttpPostedFileBase)new MemoryPostedFile(buffer);
//Do whatever you want with filename and its binaray data.
try
{
if (objFile != null && objFile.ContentLength > 0)
{
string path = "Set your desired path and file name";
objFile.SaveAs(path);
//Don't Forget to save path to DB
}
}
catch (Exception ex)
{
//HANDLE EXCEPTION
}
return "OK";
}
public class MemoryPostedFile : HttpPostedFileBase
{
private readonly byte[] fileBytes;
public MemoryPostedFile(byte[] fileBytes, string fileName = null)
{
this.fileBytes = fileBytes;
this.FileName = fileName;
this.InputStream = new MemoryStream(fileBytes);
}
public override void SaveAs(string filename)
{
File.WriteAllBytes(filename, fileBytes);
}
public override string ContentType => base.ContentType;
public override int ContentLength => fileBytes.Length;
public override string FileName { get; }
public override Stream InputStream { get; }
}