简体   繁体   中英

Jquery Fileupload - Ajax pass additional variables

My project is MVC 5 c# I am using jquery.fileupload would like to know how I can pass additional values to the controller, in this case is the file description. View:

<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" />

Script:

 $(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 + '%');
        });
    });

Controller:

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

You can send additional data to server using formData property. See below:

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

The formData option can be used to set additional form data programmatically.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM