I want to upload an image and then convert it to base64.
What data type should I choose ? I tried string but it gives me only the file name but not it's path.
public class TestModel
{
public string Image { get; set; }
}
View:
@model Test.Models.TestModel
<form asp-action="Test" method="post">
<div class="form-group">
<input asp-for="Image" class="form-control" type="file" />
</div>
<div class="form-group">
<input type="submit" value="Create" class="btn btn-primary" />
</div>
</form>
CodePudding user response:
You can Use IFormFile
type to upload an image and then convert it to base64 in controller. Here is my code:
controller
public IActionResult FileUpLoad(Models.TestModel model)
{
//convert it to base64
var ms = new MemoryStream();
model.Image.CopyTo(ms);
var fileBytes = ms.ToArray();
string result = Convert.ToBase64String(fileBytes);
//......
return RedirectToAction("Index");
}
model
public class TestModel
{
public IFormFile Image { get; set; }
}
view
<div>
<form asp-controller="Home" asp-action="FileUpLoad" enctype="multipart/form-data" method="post">
<input type="file" asp-for="Image" />
<button type="submit">Submit</button>
</form>
</div>
Upload an Image and then it can be converted to base64.