I would like to upload images with .net core web api 2.1 and jquery in the post data to azure blobs with an id, then when retrieving the data, the image also is in the relevant table row (basically like a blog post).
Currently the way I upload and retrieve data to azure blobs is as follows:
web api:
[Route("api/[controller]")]
[EnableCors("MyPolicy")]
public class BlobController : Controller
{
private CloudBlobClient cloudBlobClient;
public BlobController(CloudBlobClient cloudBlobClient)
{
this.cloudBlobClient = cloudBlobClient;
}
[HttpPost()]
public OkObjectResult upload([FromForm] IFormFile file)
{
string FileName = file.FileName;
var blobfile = cloudBlobClient.GetContainerReference("container").GetBlockBlobReference(FileName);
if (blobfile.Exists())
{
}
else
{
var container = cloudBlobClient.GetContainerReference("container");
var blob = container.GetBlockBlobReference(FileName);
blob.UploadFromStream(file.OpenReadStream());
}
return Ok("uploaded");
}
[HttpGet()]
public OkObjectResult GetAll()
{
var bloblist = new ArrayList();
var container = cloudBlobClient.GetContainerReference("container");
SharedAccessBlobPolicy ReadOnly = new SharedAccessBlobPolicy()
{
SharedAccessExpiryTime = DateTime.UtcNow.AddHours(24),
Permissions = SharedAccessBlobPermissions.Read
};
var sas = container.GetSharedAccessSignature(ReadOnly);
foreach (var blob in container.ListBlobs())
{
bloblist.Add(blob.Uri + sas);
}
return Ok(bloblist);
}
}
html/js for image upload and viewing:
<div align="center">
<form method="post" action="" enctype="multipart/form-data" id="myform">
<div>
<input type="file" id="file" name="file" />
<input type="button" class="button" value="Upload"
id="but_upload">
</div>
</form>
<div>
<input type="button" id="but_display" value="show all uploaded images">
<div id="stage">
</div>
</div>
</div>
@section Scripts {
<script type="text/javascript">
$("#but_upload").click(function () {
var fd = new FormData();
var files = $('#file')[0].files[0];
fd.append('file', files);
$.ajax({
url: 'https://localhost:44331/api/blob/',
type: 'post',
data: fd,
contentType: false,
processData: false,
success: function (response) {
if (response != 0) {
alert('file uploaded');
}
else {
alert('file not uploaded');
}
},
});
});
$("#but_display").click(function () {
$.ajax({
url: 'https://localhost:44331/api/blob/',
type: 'get',
success: function (response) {
$("#stage").empty();
response.forEach((url) => {
$("#stage").append("<img src='" + url + "' width='200' >");
})
}
});
});
</script>
}
Any help will be greatly appreciated.