I have asp.net mvc and asp.net core 3.1 amazon s3 projects. I am loading excel file in asp.net mvc and this excel file is saved in amazon s3. I performed the registration to amazon s3 with asp.net core web api. I use ajaxForm for file upload. What I want to try is to direct the file upload process to asp.net core web api via mvc controller. Another issue I can not do is to save the data contained in the file to the sql database after the excel file is saved in amazon s3. I tried to find results from different sources, but I was not successful. How can I do that?
This is my MVC View code:
@using (Html.BeginForm("Index", "Admin", FormMethod.Post, new { enctype = "multipart/form-data", id = "Myform" }))
{
<div class="form-group mb-3">
<div class="custom-file">
<input type="file" class="custom-file-input" id="FileUpload" name="FileUpload">
<label class="custom-file-label" for="FileUpload"></label>
</div>
</div>
<button type="submit" id="Submit" class="btn btn-primary"><i class="fa fa-upload" aria-hidden="true"></i> Yükle</button>
<button type="button" id="export" class="btn btn-primary"><i class="fa fa-file-excel-o" aria-hidden="true"></i> Excel'e Aktar</button>
<br /><br />
<ul id="ulList"></ul>
}
This is my javascript code:
$('#Myform').ajaxForm({
beforeSend: function () {
noFiles();
$("#ulList").empty();
$('.progress-bar').width(percentVal);
loader_icon.show();
},
uploadProgress: function (event, position, total, percentComplete) {
var fp = $("#FileUpload");
var lg = fp[0].files.length; // get length
var items = fp[0].files;
var fragment = "";
// disable button
$("#Submit").prop("disabled", true);
// add spinner to button
$("#Submit").html(
`<span style="@@keyframes spinner-border {
to { transform: rotate(360deg); }
}
.spinner-border{
display: inline-block;
width: 2rem;
height: 2rem;
vertical-align: text-bottom;
border: .25em solid currentColor;
border-right-color: transparent;
border-radius: 50%;
-webkit-animation: spinner-border .75s linear infinite;
animation: spinner-border .75s linear infinite;
}
.spinner-border-sm{
height: 1rem;
border-width: .2em;
}" class="spinner-border spinner-border-sm" role="status" aria-hidden="true"></span> Yükleniyor...`
);
if (lg > 0) {
fragment += "<li> Veriler yükleniyor..</li>";
$("#ulList").append(fragment);
for (var i = 0; i < lg; i++) {
var i = 0;
if (i == 0) {
i = 1;
var elem = document.getElementById("myBar");
var width = 0;
var id = setInterval(frame, 100);
function frame() {
if (width >= 100) {
swal({
title: "Başarılı!",
text: "Kayıt Başarılı!",
type: "success",
showCancelButtonClass: "btn-primary",
confirmButtonText: "OK"
});
clearInterval(id);
i = 0;
elem.style.width = "0%";
$("#Submit").prop("disabled", false);
$("#export").prop("disabled", false);
$("#Submit").html("Yükle");
$("#ulList").empty();
var lastFile =$("#onceki").val();
console.log(lastFile);
var prevFile = $("#oncekii").val();
console.log(prevFile);
$.cookie('oncekiYuklenenDosya', lastFile, { expires: 365 });
$.cookie('dahaOncekiYuklenenDosya', prevFile, { expires: 365 });
@*$.ajax({
type: "GET",
url: '@Url.Action("AddMap","Admin")',
success: function (data) {
console.log(data);
},
error: function (error) {
alert(error);
}
});*@
//var myUrl = "myApiUrl";
//var formData = new FormData();
//formData.append("FileUpload", $("#FileUpload").file);
// $.ajax({
// type: "POST",
// url: myUrl,
// data: formData,
// crossDomain: true,
// dataType: 'html',
// contentType: "multipart/form-data",
// headers: {
// //Authorization: "Bearer " + accesstoken,
// 'Access-Control-Allow-Origin': '*'
// },
// success: function (data) {
// alert(data);
// },
// error: function (error) {
// alert(error);
// }
//});
showMap();
} else {
width++;
elem.style.width = width + "%";
elem.innerHTML = width + "%";
}
}
}
}
}
},
complete: function (xhr) {
if (xhr.success == true) {
swal({
title: "Başarılı!",
text: "Kayıt Başarılı!",
type: "success",
showCancelButtonClass: "btn-primary",
confirmButtonText: "OK"
});
}
}
});
This is the mvc controller I want to redirect to the web api:
[HttpPost]
public ActionResult Index(FormCollection formCollection)
{
HttpPostedFileBase file = Request.Files["FileUpload"];
var json = JsonConvert.SerializeObject(
new
{
files = file,
Passed = true,
Mesaj = "item added"
},
new HttpPostedFileConverter());
var stringContent = new StringContent(json, Encoding.UTF8, "multipart/form-data");
try
{
using (var client = new HttpClient())
{
//var userid = Session["UserID"];
client.BaseAddress = new Uri("myApiUrl");
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("multipart/form-data"));
//HttpResponseMessage response = await client.PostAsJsonAsync("api/address/postmap?mapList=" + mapList).Result;
HttpResponseMessage response = client.PostAsync("api/address/save?FileUpload=", stringContent).Result;
if (response.IsSuccessStatusCode)
{
return RedirectToAction("Index", "Admin");
}
return null;
}
}
catch (Exception e)
{
ViewBag.Hata = e.Message;
}
return RedirectToAction("Index", "Admin");
}
This is my asp.net core 3.1 web api controller:
[HttpPost]
[Route("api/address/save")]
public async Task<IActionResult> Save(IFormFile FileUpload)
{
var userId = _httpContextAccessor.HttpContext.User.FindFirst(ClaimTypes.NameIdentifier).Value;
var uid = Convert.ToInt32(userId);
if (FileUpload.Length == 0)
{
return BadRequest("please provide valid file");
}
var fileName = ContentDispositionHeaderValue
.Parse(FileUpload.ContentDisposition)
.FileName
.TrimStart().ToString();
var folderName = Request.Form.ContainsKey("folder") ? Request.Form["folder"].ToString() : null;
bool status;
using (var fileStream = FileUpload.OpenReadStream())
using (var ms = new MemoryStream())
{
await fileStream.CopyToAsync(ms);
status = await _awsS3Service.UploadFileAsync(ms, fileName, folderName);
var mapList = new List<Map>();
using (var package = new ExcelPackage(ms))
{
ExcelWorksheet worksheet = package.Workbook.Worksheets[0];
var rowCount = worksheet.Dimension.Rows;
for (int row = 2; row <= rowCount; row++)
{
mapList.Add(new Map
{
UserId = uid,
Latitude = worksheet.Cells[row, 1].Value.ToString().Trim(),
Longitude = worksheet.Cells[row, 2].Value.ToString().Trim(),
});
}
}
foreach (var item in mapList)
{
dbContext.Map.Add(item);
}
dbContext.SaveChanges();
}
return status ? Ok("success")
: StatusCode((int)HttpStatusCode.InternalServerError, $"error uploading {fileName}");
}
Where do you think I'm making a mistake? Thank you.