使用 Ajax MVC .NET 6 上传文件

问题描述 投票:0回答:1

我需要使用Ajax将图像(单个)上传到服务器。 Action 将调用我的 API 控制器上的 post 方法。

到目前为止,我只发现过时且损坏的解决方案,如下所示:

https://www.c-sharpcorner.com/UploadFile/manas1/upload-files-through-jquery-ajax-in-Asp-Net-mvc/

或者这个:在Asp.Net Core中使用Ajax上传文件

此外,令人惊讶的是,微软文档中的示例在我的情况下也不起作用,https://learn.microsoft.com/en-us/aspnet/core/mvc/models/file-uploads?view=aspnetcore-2.1 #将名称属性值与后方法的参数名称匹配

List<IFormFile> files
为空,我不知道为什么。

我当前的代码:

HTML

<form id="InputBannerForm"  action="@Url.Action("UploadLocalBanner", "Api")" enctype="multipart/form-data" onsubmit="AJAXSubmit(this);return false;" method="post" >
                            <div class="row justify-content-center">
                                <div class="col-12 col-md-6 mb-3">
                            <div>
                            <label for="InputBanner" class="col-12"  >@Localizer["banner"]</label>
                            <input id="InputBanner" type="file" accept="image/jpeg, image/png" onchange="onInputBannerChange()">
                      </div>
                </div>
           </div>
    </form>

JS:

function onInputBannerChange() {
    document.getElementById("InputBannerForm").submit();
}

async function AJAXSubmit(oFormElement) {
    var resultElement = oFormElement.elements.namedItem("result");
    const formData = new FormData(oFormElement);

    try {
        const response = await fetch(oFormElement.action, {
            method: 'POST',
            body: formData
        });

        if (response.ok) { console.log("succes"); }

        resultElement.value = 'Result: ' + response.status + ' ' +
            response.statusText;
    } catch (error) {
        console.error('Error:', error);
    }
}

控制器:

[Route("SO-{clientId}/{controller}/{action}")]
[HttpPost]
public async Task<IActionResult> UploadLocalBanner(IList<IFormFile> files)
{
    try
    {
        IFormFile source = files[0];
        string filename = System.Net.Http.Headers.ContentDispositionHeaderValue.Parse(source.ContentDisposition).FileName.Trim('"');

        if (filename.Contains("\\"))
            filename = filename.Substring(filename.LastIndexOf("\\") + 1);

        string relativePath = "wwwroot\\Images\\LocalBanners";

        string targetDirectory = System.IO.Path.Combine(System.IO.Directory.GetCurrentDirectory(), relativePath);
        if (!System.IO.Directory.Exists(targetDirectory))
            System.IO.Directory.CreateDirectory(targetDirectory);

        using (System.IO.FileStream output = System.IO.File.Create(System.IO.Path.Combine(targetDirectory, filename)))
        {
            await source.CopyToAsync(output);
        }
    
        return Ok();
    }
    catch(Exception ex)
    {
        return BadRequest(ex);
    }
}
javascript c# ajax model-view-controller .net-6.0
1个回答
0
投票

我设法用这段代码实现我的目标:

    <div id="TableHeader" class="row header">
        <h3 >@Localizer["_Local Banners List_ : "]</h3>
        <input type="file" id="imageUploadForm"  name="image" multiple="multiple" />
    </div>

这是我的 Ajax 请求:

$(document).ready(function() {
    $("#imageUploadForm").change(function() {
        var formData = new FormData();
        var totalFiles = document.getElementById("imageUploadForm").files.length;
        for (var i = 0; i < totalFiles; i++) {
            var file = document.getElementById("imageUploadForm").files[i];
            formData.append("imageUploadForm", file);
        }
        formData.append("localId", @Model.LocalId);

        $.ajax({
            type: "POST",
            url: _UploadLocalBannerImage,
            data: formData,
            dataType: 'json',
            contentType: false,
            processData: false
        }).done(function() { alert('success'); }).fail(function(xhr, status, errorThrown) { alert('fail'); });
    });
});

这就是我在服务器上处理请求的方式:

    [HttpPost]
    public IActionResult UploadasdaLocalBannerImage(int localId)
    {

        if (Request.Form.Files.Count != 0)
        {
            for (int i = 0; i < Request.Form.Files.Count; i++)
            {
                var file = Request.Form.Files[i];
                // var fileName = System.IO.Path.GetFileName(file.FileName);

                // some logic before aploading file and prepearing
                
                string absolutePath = System.IO.Path.Combine(Environment.CurrentDirectory, "path to file");
                using (var stream = new System.IO.FileStream(absolutePath, System.IO.FileMode.Create))
                {
                    file.CopyTo(stream);
                }

                // some logic after file uploaded

                return Ok();
                //file.SaveAs(path);
            }

        }
        return BadRequest();

    }
© www.soinside.com 2019 - 2024. All rights reserved.