是否有任何方法从服务到web api获取数据



我正在尝试通过worker服务将文件的数据块发送到web api。但是块不能被web api接收,这是我的代码

下面是worker service的一些代码

int chunkSize = 100;
using (Stream streamx = new FileStream(filePath, FileMode.Open, FileAccess.Read))
{
byte[] buffer = new byte[chunkSize];

int bytesRead = 0;
long bytesToRead = streamx.Length;
while (bytesToRead > 0)
{
int n = streamx.Read(buffer, 0, chunkSize);
if (n == 0) break;
// Let's resize the last incomplete buffer
if (n != buffer.Length)
Array.Resize(ref buffer, n);
MultipartFormDataContent form = new MultipartFormDataContent();
HttpContent byteContent = new ByteArrayContent(buffer);
form.Add(byteContent, "fileByte");
HttpResponseMessage response1 = null;
try
{
response1 = client.PostAsync("http://localhost:15594/weatherforecast/PostData", form).Result;
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
var k = response1.Content.ReadAsStringAsync().Result;
response = null;
bytesRead += n;
bytesToRead -= n;
}

下面是一些web api的代码

[HttpPost]
[Route("PostData")]
public IActionResult PostData()
{
var request = HttpContext.Request;

var vals = request.Form.TryGetValue("fileByte", out StringValues sv).ToString();
NameValueCollection vals2 = new NameValueCollection();
int count = vals2.Count;
string cv = null;
foreach(var i in vals2)
{
cv += i;
}
} 

这里我已经解决了这个问题,基本上我想上传一个文件块,这里是文件上传到webapi的代码,

int chunkSize = 1024

using (Stream streamx = new FileStream(filePath, FileMode.Open, FileAccess.Read))
{
byte[] buffer = new byte[chunkSize];

int bytesRead = 0;
long bytesToRead = streamx.Length;

while (bytesToRead > 0)
{

int n = streamx.Read(buffer, 0, chunkSize);

if (n == 0) break;

if (n != buffer.Length)
Array.Resize(ref buffer, n);

MultipartFormDataContent multiContent = new MultipartFormDataContent();
ByteArrayContent bytes = new ByteArrayContent(buffer);
multiContent.Add(bytes, "file", fi.Name);


HttpResponseMessage response1 = null;
try
{
response1 = client.PostAsync("http://localhost:15594/weatherforecast/PostData", multiContent).Result;

}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}

var k = response1.Content.ReadAsStringAsync().Result;
response = null;

bytesRead += n;
bytesToRead -= n;

}
}

"下面是webapi

的代码片段"

[HttpPost](路线("PostData")

public IActionResult PostData()
{​​​​​​​

var form = Request.Form;
foreach (var formFile in form.Files)
{​​​​​​​

var fileName = formFile.FileName;

var savePath = Path.Combine(@"E:Program_210302_1WebApplication_API_210302_1WebApplication_APIwwwroot", fileName);

using (var fileStream = new FileStream(savePath, FileMode.Append))
{​​​​​​​
formFile.CopyTo(fileStream);
}​​​​​​​
}​​​​​​​

}​​​​​​​

"

最新更新