Asp.net mvc 如何从视图向控制器发送和显示图像?
我的项目有两个控制器:mvc和api。图像已成功从视图传递到mvc控制器,问题是如何将其从mvc控制器发送到api控制器Asp.net mvc 如何从视图向控制器发送和显示图像?,asp.net-mvc,asp.net-core,asp.net-core-webapi,Asp.net Mvc,Asp.net Core,Asp.net Core Webapi,我的项目有两个控制器:mvc和api。图像已成功从视图传递到mvc控制器,问题是如何将其从mvc控制器发送到api控制器 [HttpPost] public IActionResult Create(ProductSubCategoryviewmodel productSubCategory) { if (ModelState.IsValid) { string uniqueFileName = UploadedFile(
[HttpPost]
public IActionResult Create(ProductSubCategoryviewmodel productSubCategory)
{
if (ModelState.IsValid)
{
string uniqueFileName = UploadedFile(productSubCategory);
ProductSubCategoryviewmodel category = new ProductSubCategoryviewmodel();
{
category.ProductSubCategoryName = productSubCategory.ProductSubCategoryName;
category.Rate = productSubCategory.Rate;
category.DisplayOrder = productSubCategory.DisplayOrder;
category.Image = uniqueFileName;
};
}
HttpClient client = api.FromApi();
var prosubjson = JsonConvert.SerializeObject(productSubCategory);
var buffer = Encoding.UTF8.GetBytes(prosubjson);
var byteContent = new ByteArrayContent(buffer);
byteContent.Headers.ContentType = new MediaTypeHeaderValue("application/json");
try
{
var result = client.PostAsync("api/ProductSubCategories", byteContent).Result;
// TODO: Add insert logic here
return RedirectToAction(nameof(Index));
}
catch
{
return View();
}
}
private string UploadedFile(ProductSubCategoryviewmodel productSubCategory)
{
string uniqueFileName = null;
if (productSubCategory.Image != null)
{
string uploadsFolder = Path.Combine(hostEnvironment.WebRootPath, "Images");
uniqueFileName = Guid.NewGuid().ToString() + "_" + productSubCategory.Image;
string filePath = Path.Combine(uploadsFolder, uniqueFileName);
using (var fileStream = new FileStream(filePath, FileMode.Create))
{
productSubCategory.Image.CopyTo(fileStream);
}
}
return uniqueFileName;
}
它显示错误:没有给出与所需的形式参数“destination”对应的参数“string.CopyTo(int,char[],int,int)”。强调文本为简单起见,只是为了说明它可以是这样的。
public class MyService
{
public void MyTestMethod()
{
// Logic code here
}
}
public class MyApiController : Controller
{
public IActionResult MyApiMethod()
{
MyService myService = new MyService();
myService.MyTestMethod();
}
}
public class MyMVCController : Controller
{
public IActionResult MyMVCMethod()
{
MyService myService = new MyService();
myService.MyTestMethod();
}
}
如何从视图向控制器发送和显示图像
[HttpPost]
public IActionResult Create(ProductSubCategoryviewmodel productSubCategory)
{
if (ModelState.IsValid)
{
string uniqueFileName = UploadedFile(productSubCategory);
ProductSubCategoryviewmodel category = new ProductSubCategoryviewmodel();
{
category.ProductSubCategoryName = productSubCategory.ProductSubCategoryName;
category.Rate = productSubCategory.Rate;
category.DisplayOrder = productSubCategory.DisplayOrder;
category.Image = uniqueFileName;
};
}
HttpClient client = api.FromApi();
var prosubjson = JsonConvert.SerializeObject(productSubCategory);
var buffer = Encoding.UTF8.GetBytes(prosubjson);
var byteContent = new ByteArrayContent(buffer);
byteContent.Headers.ContentType = new MediaTypeHeaderValue("application/json");
try
{
var result = client.PostAsync("api/ProductSubCategories", byteContent).Result;
// TODO: Add insert logic here
return RedirectToAction(nameof(Index));
}
catch
{
return View();
}
}
private string UploadedFile(ProductSubCategoryviewmodel productSubCategory)
{
string uniqueFileName = null;
if (productSubCategory.Image != null)
{
string uploadsFolder = Path.Combine(hostEnvironment.WebRootPath, "Images");
uniqueFileName = Guid.NewGuid().ToString() + "_" + productSubCategory.Image;
string filePath = Path.Combine(uploadsFolder, uniqueFileName);
using (var fileStream = new FileStream(filePath, FileMode.Create))
{
productSubCategory.Image.CopyTo(fileStream);
}
}
return uniqueFileName;
}
根据您的代码,我假设您正在使用IFormFile将图像从视图发送到控制器,但我不确定您正在使用哪个数据类型存储在数据库中,base64字符串还是字节数组。在我看来,我更喜欢使用字节数组来存储上传文件
更多详细信息,请检查以下代码:
模型中的代码:
public class Movie
{
public int Id { get; set; }
public string Title { get; set; }
[DataType(DataType.Date)]
public DateTime ReleaseDate { get; set; }
public string Genre { get; set; }
public decimal Price { get; set; }
[MaxLength]
public byte[] Poster { get; set; }
}
和视图模型(使用此视图模型将文件上载到控制器)
控制器中的代码:
// GET: Movies/Create
public IActionResult Create()
{
return View();
}
// POST: Movies/Create
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Create(MovieViewModel model)
{
if (ModelState.IsValid)
{
Movie movie = new Movie
{
Title = model.Title,
Genre = model.Genre,
ReleaseDate = model.ReleaseDate,
Price = model.Price,
};
if (model.PosterImage != null)
{
using (var target = new MemoryStream())
{
model.PosterImage.CopyTo(target);
movie.Poster = target.ToArray(); //get the image byte array
}
}
_context.Add(movie);
await _context.SaveChangesAsync();
return RedirectToAction(nameof(Index));
}
return View(model);
}
//获取:电影/创建
public IActionResult Create()
{
返回视图();
}
//张贴:电影/创作
[HttpPost]
[ValidateAntiForgeryToken]
公共异步任务创建(MovieViewModel模型)
{
if(ModelState.IsValid)
{
电影=新电影
{
Title=model.Title,
类型=模型。类型,
ReleaseDate=model.ReleaseDate,
价格=型号。价格,
};
if(model.PosterImage!=null)
{
使用(var target=new MemoryStream())
{
model.PosterImage.CopyTo(目标);
movie.Poster=target.ToArray();//获取图像字节数组
}
}
_添加(电影);
wait_context.SaveChangesAsync();
返回重定向到操作(名称(索引));
}
返回视图(模型);
}
索引视图中的代码(使用电影模型,而不是电影视图模型):
使用
}
其他的
{
}
为什么需要将其传递给API控制器?如果原因是您想重新使用API控制器中的逻辑,也许您可以创建一个服务层,该层可以由您的API和MVC控制器使用。谢谢您的建议,您可以通过发送示例代码来帮助我吗?您可以查看我的帖子答案。有两个不同的项目,一个在MVC中,另一个在API中
@model IEnumerable<dotNetCore3_1.Models.Movie>
<table class="table">
<thead>
<tr>
...
</tr>
</thead>
<tbody>
@foreach (var item in Model) {
<tr>
...
<td>
@if (item.Poster != null)
{
<img class="img-responsive " style="width:50px; height:50px" src="data:image/jpeg;base64,@Convert.ToBase64String(item.Poster)" />
}
else
{
<img class="img-responsive " style="width:50px; height:50px" src="~/images/default.jpg" />
}
</td>
<td>
<a asp-action="Edit" asp-route-id="@item.Id">Edit</a> |
<a asp-action="Details" asp-route-id="@item.Id">Details</a> |
<a asp-action="Delete" asp-route-id="@item.Id">Delete</a>
</td>
</tr>
}
</tbody>
</table>
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Create(MovieViewModel model)
{
if (ModelState.IsValid)
{
Movie movie = new Movie
{
Title = model.Title,
Genre = model.Genre,
ReleaseDate = model.ReleaseDate,
Price = model.Price,
};
if (model.PosterImage != null)
{
using (var target = new MemoryStream())
{
model.PosterImage.CopyTo(target);
movie.Poster = target.ToArray(); //stored the image using byte array.
}
}
//consume the webapi and post the model.
using (var client = new HttpClient())
{
var requesturi = "https://localhost:44334/api/MoviesAPI";
StringContent content = new StringContent(JsonConvert.SerializeObject(movie), Encoding.UTF8, "application/json");
//HTTP POST
var postTask = client.PostAsync(requesturi, content);
postTask.Wait();
var result = postTask.Result;
if (result.IsSuccessStatusCode)
{
return RedirectToAction("Index");
}
}
//_context.Add(movie);
//await _context.SaveChangesAsync();
//return RedirectToAction(nameof(Index));
}
return View(model);
}
// POST: api/MoviesAPI
// To protect from overposting attacks, enable the specific properties you want to bind to, for
// more details, see https://go.microsoft.com/fwlink/?linkid=2123754.
[HttpPost]
public async Task<ActionResult<Movie>> PostMovie(Movie movie)
{
_context.Movie.Add(movie);
await _context.SaveChangesAsync();
return CreatedAtAction("GetMovie", new { id = movie.Id }, movie);
}