我有一个Web API,它将图像作为输入并将照片保存在某个目录中。 从Web应用程序控制器中,我将获得图像,并且需要将图像发送到Web API。 如何实现呢? Web API和Web应用程序均在Dot net core 2.1中创建
下面是代码详细信息。
Web API代码:
[Route("api/[controller]")]
[ApiController]
public class ImageTestController : ControllerBase
{
//Image upload
[HttpPost]
public async Task<string> ImageUpload([FromForm]IFormFile file)
{
if (file.Length > 0)
{
try
{
if (!Directory.Exists("actualpath"))
{
Directory.CreateDirectory("actualpath");
}
using (FileStream filestream = System.IO.File.Create("actualpath" + file.FileName))
{
file.CopyTo(filestream);
filestream.Flush();
return file.FileName;
}
}
catch (Exception ex)
{
return ex.ToString();
}
}
else
{
return "Unsuccessful";
}
}
}
Web应用程序控制器
public class SampleController : Controller
{
[HttpPost]
public ActionResult SavePhoto(IFormFile fileParameter)
{
//In fileParameter i will recieve the image
and i need to send this to Web API
}
}
.cshtml:包含kendo UI上传控件
<div class="demo-section k-content">
@(Html.Kendo().Upload()
.Name("files")
.HtmlAttributes(new { aria_label = "files" } )
.Multiple(false)
.Async(a => a
.Save("SavePhoto", "Sample")
.AutoUpload(true)
.SaveField("fileParameter")
))
</div>
在视图中,从用户获取图像后,它将在Sample控制器中单击SavePhoto方法。从控制器,我需要代码将图像发送到API。最后,我应该可以保存照片了。
答案 0 :(得分:1)
我认为最好重构您的ImageTestController
和SampleController
来共享相同的ImageUploader
服务。
// an interface that describes uploading image
public interface IImageUploader{
Task<string> UploadAsync(IFormFile file);
}
// upload an image to local file system (I just copy your code)
public class LocalImageUploader : IImageUploader{
public async Task<string> UploadAsync(IFormFile file){
if (file.Length > 0)
{
try
{
if (!Directory.Exists("actualpath"))
{
Directory.CreateDirectory("actualpath");
}
using (FileStream filestream = System.IO.File.Create("actualpath" + file.FileName))
{
await file.CopyToAsync(filestream);
filestream.Flush();
return file.FileName;
}
}
catch (System.Exception ex)
{
return ex.ToString();
}
}
else
{
return "Unsuccessful";
}
}
}
现在通过以下方式注册服务:
public void ConfigureServices(IServiceCollection services)
{
// ...
services.AddSingleton<IImageUploader,LocalImageUploader>();
}
最后,如下更改控制器:
public class ImageTestController : ControllerBase
{
private IImageUploader _uploader;
public ImageTestController(IImageUploader uploader){
this._uploader = uploader;
}
//Image upload
[HttpPost]
public async Task<string> ImageUpload([FromForm]IFormFile file)
{
var result= await this._uploader.UploadAsync(file);
return result;
}
}
public class SampleController : Controller
{
private IImageUploader _uploader;
public SampleController(IImageUploader uploader)
{
this._uploader = uploader;
}
[HttpPost]
public async Task<ActionResult> SavePhoto(IFormFile fileParameter)
{
//In fileParameter i will recieve the image
var result=await this._uploader.UploadAsync(fileParameter);
return new JsonResult(new { });
}
}
顺便说一句,我认为这不是在UploadAsync()
方法中返回魔术字符串的好方法。我更喜欢创建一个新的Result
类。
[更新]:如何使用HttpClient将图像发布到Web API
public class HttpImageUploader
{
private readonly HttpClient httpClient;
public HttpImageUploader(HttpClient client)
{
this.httpClient = client;
}
public async Task<HttpResponseMessage> UploadAsync(IFormFile file)
{
var req= new HttpRequestMessage();
req.Method = HttpMethod.Post;
// you might need to update the uri
req.RequestUri = new Uri("https://localhost:5001/api/ImageTest/");
HttpResponseMessage resp = null;
using(var fs=file.OpenReadStream())
{
var form = new MultipartFormDataContent();
var imageStream=new StreamContent(fs) ;
imageStream.Headers.ContentType= new System.Net.Http.Headers.MediaTypeHeaderValue(file.ContentType);
// because your WebAPI expects a field named as `file`
form.Add( imageStream,"file", file.FileName);
req.Content = form;
resp = await this.httpClient.SendAsync(req);
}
return resp;
}
}
services.AddHttpClient<HttpImageUploader>();
public class SampleController : Controller
{
private HttpImageUploader _uploader;
public SampleController(HttpImageUploader uploader)
{
this._uploader = uploader;
}
[HttpPost]
public async Task<ActionResult> SavePhoto([FromForm]IFormFile fileParameter)
{
var resp = await this._uploader.UploadAsync(fileParameter);
return Json(resp); // now you get the response.
}
}
ImageTestController::ImageUpload
:using (FileStream filestream = System.IO.File.Create("actualpath" + file.FileName))using (FileStream filestream = System.IO.File.Create("actualpath/" + file.FileName)) { ...