How to Upload Image Via WebApi

前端 未结 6 1013
忘了有多久
忘了有多久 2020-12-02 12:53

How I can upload Image File via ASP.NET Web API?
I have an input tag in File mode and it posted to API, how I can save it to server folder?
I tried th

6条回答
  •  渐次进展
    2020-12-02 12:56

    You can simply convert your image to a Base64String then post it as a StringContent.

    public static async Task Post(string controller, string method, string accessToken, string bodyRequest) where T : class
    {
        using (HttpClient client = new HttpClient())
        {
            client.DefaultRequestHeaders.Clear();
            client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", accessToken);
    
            var stringContent = new StringContent(bodyRequest, Encoding.UTF8, "application/json");
    
            var response = await client.PostAsync($"{Constants.ApiBaseUrl}/api/{controller}/{method}", stringContent);
            if (response.IsSuccessStatusCode)
                return response.Content as T;
        }
        return default(T);
    }
    

    bodyRequest on my code is the class/Model value to be converted to string

    using Json.Serialize(model) which also contains your image System.Convert.ToBase64String(imageBytes[]) as its property.

提交回复
热议问题