Jquery Fileupload - Ajax传递其他变量

时间:2016-03-03 07:24:41

标签: c# jquery ajax asp.net-mvc file-upload

我的项目是MVC 5 c#我正在使用jquery.fileupload想知道如何将其他值传递给控制器​​,在这种情况下是文件描述。 视图:

<i class="glyphicon glyphicon-plus"></i>
    <span>Add files...</span>
    <input id="fileupload" type="file" name="files[]" multiple>

</span>
<input id="description" name="description" value="description" />

脚本:

 $(document).ready(function () {
        var description = $("#description").val();
        $('#fileupload').fileupload({
            dataType: 'json',
            url: '/Home/UploadFiles',
            autoUpload: true,
            done: function (e, data) {
                $('.file_name').html(data.result.name);
                $('.file_type').html(data.result.type);
                $('.file_size').html(data.result.size);
            }
        }).on('fileuploadprogressall', function (e, data) {
            var progress = parseInt(data.loaded / data.total * 100, 10);
            $('.progress .progress-bar').css('width', progress + '%');
        });
    });

控制器:

public ContentResult UploadFiles()
        {
            var r = new List<UploadFilesResult>();

            foreach (string file in Request.Files)
            {
                HttpPostedFileBase hpf = Request.Files[file] as HttpPostedFileBase;
                if (hpf.ContentLength == 0)
                    continue;

                string savedFileName = Path.Combine(Server.MapPath("~/App_Data"), Path.GetFileName(hpf.FileName));
                hpf.SaveAs(savedFileName);

                r.Add(new UploadFilesResult()
                {
                    Name = hpf.FileName,
                    Length = hpf.ContentLength,
                    Type = hpf.ContentType
                });
            }
            return Content("{\"name\":\"" + r[0].Name + "\",\"type\":\"" + r[0].Type + "\",\"size\":\"" + string.Format("{0} bytes", r[0].Length) + "\"}", "application/json");
        }

1 个答案:

答案 0 :(得分:1)

您可以使用formData属性向服务器发送其他数据。 见下文:

 $('#fileupload').fileupload({
    formData: {
        param1: 'test2',
        param2: "test3",
        param3: "test3"
    }
});

formData选项可用于以编程方式设置其他表单数据。