c# 将图像从 WPF 发送到 WebAPI

Due*_*ctu 2 c# wpf asp.net-web-api

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

服务器端

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

客户端

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;
}
Run Code Online (Sandbox Code Playgroud)

url 存在,我想我需要编码为 json 格式,但我不知道如何。

谢谢你的时间!

Ram*_*usa 5

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

我建议您将参数列表变成一个单一对象,如下所示:

public class PhotoUploadRequest
{
    public string id;
    public string tr;
    public string image;
}
Run Code Online (Sandbox Code Playgroud)

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

 var buffer = Convert.FromBase64String(request.image);
Run Code Online (Sandbox Code Playgroud)

然后将其投射到HttpPostedFileBase

  HttpPostedFileBase objFile = (HttpPostedFileBase)new MemoryPostedFile(buffer);
Run Code Online (Sandbox Code Playgroud)

现在您有了图像文件。做你想做的。

完整代码在这里:

    [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";
    }
Run Code Online (Sandbox Code Playgroud)

编辑: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; }
}
Run Code Online (Sandbox Code Playgroud)