在 mvc 上使用 ajax 发送文件和文本参数

joh*_*dle 5 c# jquery asp.net-core-mvc

检查下面的jquery代码。在这里,我从 html 中抓取文件,然后通过 ajax 调用将其发布到我的 Controller Post 方法。从 Controller post 方法中,我成功地接收到该文件,files如您所见。但我的问题是我如何发送另外两个被调用的文本参数 -type并且id从这个 ajax 调用然后我怎样才能从带有该文件的控制器中获取该值?基本上我也必须用那些文本值来获取那个文件。这怎么可能?ajax 和控制器需要什么改变?

网址:

<div class="col-sm-3" style="float:left;">
                        <label class="btn btn-outline-dark btn-block">
                            Browse...
                            <span id="uploaded-file-name" style="font-style: italic"></span>
                            <input id="file-upload" type="file" name="file"
                                   onchange="$('#uploaded-file-name').text($('#file-upload')[0].value);" hidden>
                        </label>
                    </div>
                    <div class="col-sm-2" style="float:left;">
                        <button class="btn btn-dark" id="start_upload">Start Upload</button>
                    </div>
Run Code Online (Sandbox Code Playgroud)

jQuery ajax:

//file upload
        $("#start_upload").click(function (evt) {
            var fileUpload = $("#file-upload").get(0);
            var files = fileUpload.files;
            var data = new FormData();
            for (var i = 0; i < files.length; i++) {
                data.append(files[i].name, files[i]);
            }
            $.ajax({
                type: "POST",
                url: "/Products/UploadFiles",
                contentType: false,
                processData: false,
                data: data,
                success: function (message) {
                    alert(message);
                },
                error: function () {
                    alert("There was error uploading files!");
                }
            });
        });
Run Code Online (Sandbox Code Playgroud)

MVC .net 核心控制器:

[HttpPost]
public IActionResult UploadFiles()
{
    //file upload process
    var files = Request.Form.Files;

    string type = "";
    int id = ;


}
Run Code Online (Sandbox Code Playgroud)

Shy*_*yju 5

您可以将其他输入字段值添加到 FormData 对象。

我将首先创建一个用于接受 ajax 负载的视图模型

public class UploadVm
{
    public string Type { set; get; }
    public string Id { set; get; }
    public HttpPostedFileBase File { set; get; }
}
Run Code Online (Sandbox Code Playgroud)

现在,在您的视图中,再添加 2 个输入元素以从用户读取此值

<input id="id"   type="text" />
<input id="type" type="text" />
Run Code Online (Sandbox Code Playgroud)

现在在您的 ajax 调用代码中,向FormData对象添加另外 2 个项目。

$("#start_upload").click(function (evt) {

    var fileUpload = $("#file-upload").get(0);
    var files = fileUpload.files;
    var data = new FormData();

    for (var i = 0; i < files.length; i++) {
        data.append("File", files[i]);
    }

    //Add the input element values
    data.append("Type", $("#type").val());
    data.append("Id", $("#id").val());

    $.ajax({
        type: "POST",
        url: "/Products/UploadFiles",
        contentType: false,
        processData: false,
        data: data,
        success: function (message) {
            console.log(message);
        },
        error: function () {
            alert("There was error uploading files!");
        }
    });

});
Run Code Online (Sandbox Code Playgroud)

现在在您的服务器端,您可以使用我们的新视图模型作为 action 方法的参数。当进行 ajax 调用时,模型绑定器将能够映射从请求接收到的数据并将其映射到我们的UploadVm视图模型对象的属性。

[HttpPost]
public ActionResult UploadFiles(UploadVm model)
{
    // to do : read values of model and use it
    // to do : return something
}
Run Code Online (Sandbox Code Playgroud)


Lia*_*kat 5

我在这里所做的是,只需将带有值的键FormData()从 jquery 插入到此 obj 中,然后您就可以从控制器中获取它。如果您想了解更多信息,FormData()阅读此处

将你的 jquery 更改为这样-

//file upload
        $("#start_upload").click(function (evt) {
            var fileUpload = $("#file-upload").get(0);
            var files = fileUpload.files;
            var data = new FormData();
            data.append('type', 'your_type');
            data.append('id', '1');

            for (var i = 0; i < files.length; i++) {
                data.append(files[i].name, files[i]);
            }
            $.ajax({
                type: "POST",
                url: "/Products/UploadFiles",
                contentType: false,
                processData: false,
                data: data,
                success: function (message) {
                    alert(message);
                },
                error: function () {
                    alert("There was error uploading files!");
                }
            });
        });
Run Code Online (Sandbox Code Playgroud)

然后通过控制器中的键获取这些值:

[HttpPost]
public IActionResult UploadFiles()
{
    //file upload process
    var files = Request.Form.Files;
    string type = Request.Form.Where(x => x.Key == "type").FirstOrDefault().Value;
    string id = Request.Form.Where(x => x.Key == "id").FirstOrDefault().Value;

}
Run Code Online (Sandbox Code Playgroud)