目前我的 webAPI 有以下 POST 端點:
public async Task<ActionResult<string>> AddUserImage([FromRoute] string userId, [FromHeader] bool doNotOverwrite, [FromBody] byte[] content, CancellationToken ct)
我的目標是將影像檔案發送到端點。但是,我找不到通過 Internet 發送 octect-stream 或 ByteArrayContent 或其他型別的正確方法。所有嘗試都以 HTTP 415 結束。
這是我通過互聯網發送影像的最佳嘗試:
public async Task<bool> AddOrReplaceImage(string id, string endpoint, byte[] imgBinary)
{
if (imgBinary is null) throw new ArgumentNullException(nameof(imgBinary));
var request = new HttpRequestMessage(HttpMethod.Post, endpoint);
request.Headers.Add("doNotOverwrite", "false");
request.Content = JsonContent.Create(imgBinary);
// I also tried: request.Content = new ByteArrayContent(imgBinary);
request.Content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream"); // Does not seem to change a thing
var apiResult = await new HttpClient().SendAsync(request); // Returns 415
return apiResult.IsSuccessStatusCode;
}
我懷疑端點的引數和我發送 HTTP 請求的方式。我怎樣才能通過互聯網簡單地接收和發送影像?
uj5u.com熱心網友回復:
第一個解決方案:-在我的情況下有效。
您可以像這樣嘗試 [FromForm] 和 IFormFile :-
如果控制器使用 [ApiController] 注釋,則需要 [FromXxx]。對于普通視圖控制器,它可以保留。
public class PhotoDetails
{
public string id {get;set;}
public string endpoint {get;set;}
public IFormFile photo {get;set;}
}
public async Task<ActionResult<string>> AddUserImage([FromForm] PhotoDetails photoDetails, CancellationToken ct)
我在 .net 核心中嘗試過這個并且它有效,但我需要檔案陣列,所以我使用 [FromForm] 和 IFormFile[] 并從角度發送。
第二種解決方案:-我嘗試使用問題代碼復制問題場景。

然后改變了實作,它奏效了。請找到以下代碼
PhotoDetails photopara = new PhotoDetails();
photopara.id = id;
photopara.endpoint = endpoint;
photopara.photo = imgdata;
string json = JsonConvert.SerializeObject(photopara);
var stringContent = new StringContent(json, Encoding.UTF8, "application/json");
using (var client = new HttpClient())
{
var response = await client.PostAsync("http://localhost:57460/WeatherForecast", stringContent);
if (!response.IsSuccessStatusCode)
{
return null;
}
return (await response.Content.ReadAsStreamAsync()).ToString();
}
public class PhotoDetails
{
public string id {get;set;}
public string endpoint {get;set;}
public byte[] photo {get;set;}
}
在這個解決方案中,我在 photodetail 類中將 IformFile 更改為 byte[],因為 httpresponsemessage 創建問題。
在 Post 方法中獲取影像或位元組陣列

請在沒有 json 序列化的情況下嘗試這個
using (var client = new HttpClient())
using (var formData = new MultipartFormDataContent())
{
formData.Add(idContent, "id", "param1");
formData.Add(endpointContent, "endpoint", "file1");
formData.Add(bytesContent, "photo", "file2");
var response = await client.PostAsync("http://localhost:57460/WeatherForecast", formData);
if (!response.IsSuccessStatusCode)
{
return null;
}
return (await response.Content.ReadAsStreamAsync()).ToString();
}
public async Task<ActionResult<int>> AddUserImage([FromForm] PhotoDetails photo, CancellationToken ct)
{
// logic
}
仍然無法正常作業您也可以嘗試以下鏈接
使用 httpclient 發送位元組陣列
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/510737.html
上一篇:Java中http回應的字符集
