POST 使用 C# 的带有图像文件的表单数据

POST form-data with Image File using C#

我正在尝试发送 post 包含数据和图像文件的请求。但是当我在下面发送我的代码时,我收到了一个错误。请在下面查看我在客户端的代码。

    public async Task<HttpContent> PostRequestAsync(string requestUri)
    {
        string jsonString = string.Empty;
        StringContent stringJsonContent = default(StringContent);
        HttpResponseMessage requestResponse = new HttpResponseMessage();

        try
        {
            stringJsonContent = new StringContent(jsonString, Encoding.UTF8, "application/json");
            requestResponse = await this.httpClient.PostAsync(requestUri, stringJsonContent);

            if (requestResponse.IsSuccessStatusCode)
            {
                return requestResponse?.Content;
            }
            else if (requestResponse.StatusCode == HttpStatusCode.InternalServerError)
            {
            }
            else if (requestResponse.StatusCode == HttpStatusCode.Unauthorized)
            {
            }

        }
        catch (Exception ex)
        {
            throw ex.InnerException;
        }
        return requestResponse?.Content;
    }
}

在 WebAPI 上,控制器如下所示

    [HttpPost]     
    public async Task<ActionResult> UpdateProfile([FromForm] UpdateProfile updateProfile)

型号是

public class UpdateProfile:BaseModel
{

    public string firstName { get; set; }
    public string lastName { get; set; }
    public IFormFile Image { get; set; }
}

但是在 POSTMAN 中,我使用下面的方法成功上传了文件,所以我感觉我的客户端代码有问题。任何人都可以建议我需要在我的代码中添加什么才能工作?我遇到错误,无法发送请求。

在您的客户端代码中,您不使用表单对象来传输数据。 StringContent 存储表单的值而不是键。您可以使用 MultipartFormDataContent 对象来传输所有表单和文件。另外,我给出示例代码。

客户端中的代码。

class Program
{
    static async Task Main(string[] args)
    {
       await PostRequestAsync(@"D:\upload.jpg", new HttpClient(), "https://localhost:44370/api/UpdateProfile");
    }
    public static async Task<string> PostRequestAsync(string filePath,HttpClient _httpClient,string _url)
    {
        if (string.IsNullOrWhiteSpace(filePath))
        {
            throw new ArgumentNullException(nameof(filePath));
        }
        if (!File.Exists(filePath))
        {
            throw new FileNotFoundException($"File [{filePath}] not found.");
        }

        //Create form
        using var form = new MultipartFormDataContent();
        var bytefile = AuthGetFileData(filePath);
        var fileContent = new ByteArrayContent(bytefile);
        fileContent.Headers.ContentType = MediaTypeHeaderValue.Parse("multipart/form-data");
        form.Add(fileContent, "Image", Path.GetFileName(filePath));

        //the other data in form
        form.Add(new StringContent("Mr."), "firstName");
        form.Add(new StringContent("Loton"), "lastName");
        form.Add(new StringContent("Names--"), "Name");
        var response = await _httpClient.PostAsync($"{_url}", form);
        response.EnsureSuccessStatusCode();
        var responseContent = await response.Content.ReadAsStringAsync();

        return responseContent;
    }

    //Convert file to byte array
    public static byte[] AuthGetFileData(string fileUrl)
    {
        using (FileStream fs = new FileStream(fileUrl, FileMode.OpenOrCreate, FileAccess.ReadWrite))
        {
            byte[] buffur = new byte[fs.Length];
            using (BinaryWriter bw = new BinaryWriter(fs))
            {
                bw.Write(buffur);
                bw.Close();
            }
            return buffur;
        }
    }
}

WebApi中的动作

[ApiController]
[Route("[controller]")]
public class ApiController:Controller
{
    [HttpPost("get")]
    public string get([FromForm]UpdateProfile updateProfile)
    {
        return "get";
    }
    [HttpPost("UpdateProfile")]
    public async Task<ActionResult> UpdateProfile([FromForm] UpdateProfile updateProfile)
    {
        return Json("The result data "); 
    }
}

模特

public class UpdateProfile : BaseModel
{
    public string firstName { get; set; }
    public string lastName { get; set; }
    public IFormFile Image { get; set; }
}
public class BaseModel
{
    public string Name { get; set; }
}

结果: