第一部分:编写webApi接口,接受客户端的文件流,再将文件流存为图片
/// <summary>
/// 上传FQC检测图片
/// </summary>
/// <param name="checkId">检测单号</param>
/// <param name="macNum">机台号</param>
/// <param name="imageName">图片名称(如1001.bmp)</param>
/// <returns></returns>
[HttpPost]
public async Task<IActionResult> UploadFQCImage(string checkId, string macNum, string imageName)
{
var result = new BaseResult { code = 1 };
try
{
var request = this.HttpContext.Request;
request.EnableBuffering();
var requestReader = new StreamReader(request.Body);
var requestContent = await requestReader.ReadToEndAsync();
request.Body.Position = 0;
if (requestContent.Length > 0)
{
string webRootPath = _env.WebRootPath;
string subpath = $@"FQC\{macNum}\{DateTime.Today.ToString("yyyy-MM-dd")}\";
string FilePath = $@"{webRootPath}\upload\{subpath}";
DirectoryInfo di = new DirectoryInfo(FilePath);
if (!di.Exists)
{
di.Create();
}
var imgUrl = subpath + imageName;
var fullName = FilePath + @"\" + imageName;
//将收到的流存成文件
using var fileStream = System.IO.File.Create(fullName);
await requestReader.BaseStream.CopyToAsync(fileStream);
await fileStream.FlushAsync();
result.code = 200;
result.msg = $"文件{imgUrl}上传成功";
}
else
{
result.msg = "此接口通过文件流上传图片,接口未获取到文件流!";
}
}
catch (Exception ex)
{
result.msg = ex.Message;
}
return Ok(result);
}
第二部分:将图片转为流,然后调用上面的WebApi接口进行图片上传
/// <summary>
/// 测试上专FQC图片接口(临时用)
/// </summary>
/// <returns></returns>
[HttpPost]
public IActionResult UploadReport()
{
//以下几个变量可移为参数,直接这样写是为了方便测试
var path = @"D:\23.bmp";
using (var client = new HttpClient())
{
FileStream stream = new FileStream(path, FileMode.Open, FileAccess.Read);
var content = new StreamContent(stream);
//接收流的接口地址 (某次我忘了加控制器Home,导致post失败)
var url = "http://127.0.0.1:8080/api/Upload/UploadFQCImage?checkId=1&macNum=D12&imageName=23.bmp";
HttpResponseMessage response = client.PostAsync(url, content).Result;
stream.Dispose();
response.EnsureSuccessStatusCode();
var res = response.Content.ReadAsStringAsync().Result;
return Ok(res);
}
}
作者:Roy yi 于南阳