【问题标题】:c# Send image from WPF to WebAPIc# 将图像从 WPF 发送到 WebAPI
【发布时间】:2023-04-05 11:07:01
【问题描述】:

我有一个接收图像和相关数据的 WebAPI 2.1 服务 (ASP.Net MVC 4)。 我需要从 WPF 应用程序发送此图像,但出现 404 not found 错误。

服务器端

[HttpPost]
[Route("api/StoreImage")]
public string StoreImage(string id, string tr, string image)
{
    // Store image on server...
    return "OK";
}

客户端

public bool SendData(decimal id, int time, byte[] image)
{
    string url = "http://localhost:12345/api/StoreImage";
    var wc = new WebClient();
    wc.Headers.Add("Content-Type", "application/x-www-form-urlencoded");
    var parameters = new NameValueCollection()
    {
        { "id", id.ToString() },
        { "tr", time.ToString() },
        { "image", Convert.ToBase64String(image) }
    };
    var res=wc.UploadValues(url, "POST", parameters);
    return true;
}

url存在,我需要编码成json格式,但不知道怎么做。

感谢您的宝贵时间!

【问题讨论】:

标签: c# wpf asp.net-web-api


【解决方案1】:

您案例中的方法参数以QueryString 形式接收。

我建议你把参数列表变成一个像这样的对象:

public class PhotoUploadRequest
{
    public string id;
    public string tr;
    public string image;
}

然后在你的 API 中将字符串从Base64String 转换为缓冲区,如下所示:

 var buffer = Convert.FromBase64String(request.image);

然后将其转换为HttpPostedFileBase

  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";
    }

编辑: 我忘了为MemoryPostedFile 类添加代码

 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; }
}

【讨论】:

  • 感谢@Ramy,它有效!
  • @RamyMohamed 嗨,函数第二行中的 MemoryPostedFile 是什么。我在 MSDN 中找不到任何内容..
  • @MilindThakkar 再次检查答案,我更新了。
  • @RamyMohamed:谢谢,我会试一试并更新。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-06-17
  • 2013-01-23
  • 2012-03-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多