簡體   English   中英

Installing asp.net mvc excel file and asp.net core web api forwarding via mvc controller

[英]Installing asp.net mvc excel file and asp.net core web api forwarding via mvc controller

我有 asp.net mvc 和 asp.net core 3.1 amazon s3 項目。 我在 asp.net mvc 中加載 excel 文件,這個 excel 文件保存在亞馬遜 s3 中。 我使用 asp.net 核心 web api 對亞馬遜 s3 進行了注冊。 我使用 ajaxForm 進行文件上傳。 我想嘗試的是通過mvc Z594C1003F2C6E04 將文件上傳過程定向到 asp.net 核心 web api 我不能做的另一個問題是在將 excel 文件保存在 amazon s3 中后,將文件中包含的數據保存到 sql 數據庫中。 我試圖從不同的來源尋找結果,但沒有成功。 我怎樣才能做到這一點?

這是我的 MVC 查看代碼:

@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>
                }

這是我的 javascript 代碼:

$('#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"
                    });

                }
            }

        });

這是 mvc controller 我想重定向到 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");
    }

這是我的 asp.net 內核 3.1 web api Z594C103F2C6E004C3D8AB05C

[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}");
    }

你認為我在哪里犯了錯誤? 謝謝你。

好的,你有幾個不同的問題。 答案涉及幾個不同的部分,包括服務器端(您的 C# ASP.Net Core UI 和 C#.Net Core 控制器)和客戶端(您的 ASP.Net Core/Razor 標記和 Javascript)。

另外:我使用術語“ASP.Net Core”來將其與舊的“ASP.Net MVC”區分開來。

讓我們分解一下:

  1. MVC View code (我假設這是一個 ASP.Net Core “頁面”):乍一看,看起來還不錯。

  2. javascript code :看起來不錯。 但我不確定你是否需要它...

    問:你是從你的 MVC 視圖代碼中調用它嗎? 如果是這樣,怎么做? 你能給我們看看嗎? 如果不是,為什么不呢?

  3. mvc controller I want to redirect to the web api :我不確定這是什么,或者你是否需要它。

  4. asp.net core 3.1 web api controller

    ...但我認為您可以將所有這些功能移至 ASP.Net Core“發布”處理程序。

建議:

  1. 您的初始“索引”頁面處理程序將如下所示:

https://docs.microsoft.com/en-us/aspnet/core/mvc/models/file-uploads?view=aspnetcore-3.1

索引.cshtml:

<form enctype="multipart/form-data" method="post">
    <dl>
        <dt>
            <label asp-for="FileUpload.FormFile"></label>
        </dt>
        <dd>
            <input asp-for="FileUpload.FormFile" type="file">
            <span asp-validation-for="FileUpload.FormFile"></span>
        </dd>
    </dl>
    <input asp-page-handler="Upload" class="btn" type="submit" value="Upload" />
</form>
  1. 您將擁有一個看起來像這樣的“Post”處理程序:

https://docs.microsoft.com/en-us/aspnet/core/mvc/models/file-uploads?view=aspnetcore-3.1

index.cshtml.cs:

public async Task<IActionResult> OnPostUploadAsync(List<IFormFile> files)
{
    long size = files.Sum(f => f.Length);

    foreach (var formFile in files)
    {
        if (formFile.Length > 0)
        {
            var filePath = Path.GetTempFileName();

            using (var stream = System.IO.File.Create(filePath))
            {
                await formFile.CopyToAsync(stream);
            }
        }
    }

    // Process uploaded files
    // Don't rely on or trust the FileName property without validation.

    return Ok(new { count = files.Count, size });
}
  1. 這將滿足您的第一個要求:將文件上傳到您的 .Net Core web 服務器。

  2. 該文件是否恰好是 Excel 電子表格、a.jpg 圖像或文本文件並不重要——您只是在上傳一個“文件”。

  3. 您可以使用適用於.Net 的 AWS SDK 修改“OnPostUploadAsync()”處理程序以將文件發送到 S3 實例:

    https://docs.aws.amazon.com/AmazonS3/latest/dev/HLuploadFileDotNet.html

  4. 您還可以修改“OnPostUploadAsync()”以將文件寫入 SQL 數據庫:

    https://www.c-sharpcorner.com/article/upload-files-in-azure-blob-storage-using-asp-net-core/

  5. 如果您希望能夠在運行時選擇“將文件保存到服務器”、“將文件上傳到 S3”或“將文件寫入 MSSQL”,那么

    • 將單選按鈕或復選框添加到您的 Index.cshtml 標記
    • 讀取值並從“OnPostUploadAsync()”處理程序中調用適當的方法。

https://en.wikipedia.org/wiki/ASP.NET_MVC

ASP.NET MVC 是 Microsoft 開發的已停產的 web 應用程序框架,它實現了模型-視圖-控制器 (MVC) 模式。 它是開源軟件,除了專有的 ASP.NET Web Forms 組件。

ASP.NET Core has since been released, which unified ASP.NET, ASP.NET MVC, ASP.NET Web API, and ASP.NET Web Pages (a platform using only Razor pages). MVC 6 因 Core 而被放棄,預計不會發布。 Core 目前計划並入.NET 5

請記住 -.Net Core(無論是 ASP.Net Core“頁面”還是.Net Core“控制器”)只是 HTTP 請求和響應之上的一個抽象層 最終,這一切都只是 HTTP GET 和 POST。 不是“控制器”,不是“頁面”。

是的,您可以將 POST 請求處理程序放入“控制器”(而不是 ASP.Net Core“頁面”)。 您所要做的就是1)編寫新的,Z594C103F2C6E04C3D8AB059F031E0C1E0C1AZ模塊,2)使用上面發布的相同代碼,3)確保您定義了<form>路由默認值。

十分簡單。

但我敦促你以我的方式嘗試。

讓它工作。

然后,一旦它開始工作......一旦你更好地理解它是如何工作的,然后擴展你的解決方案。

朝着您的解決方案邁出“小步”。 這是一篇關於這個主題的好文章:

https://blog.adrianbolboaca.ro/2013/01/the-history-of-taking-baby-steps/

不要氣餒。

祝你好運。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM