js方法实现--上传文件功能

function createUploadForm(fileElementId, data, curFileList) {
    var id = new Date().getTime();
    var formId = 'jUploadForm' + id; //给form添加一个独一无二的id
    var form = jQuery('<form  action="" method="POST" name="' + formId + '" id="' + formId + '" enctype="multipart/form-data" ></form>'); //创建form元素
    if (data) {
        for (var i in data) {
            jQuery('<input type="hidden" name="' + i + '" value="' + data[i] + '" />').appendTo(form);
        }
    }

    //set attributes
    jQuery(form).css('position', 'absolute'); //给动态form添加样式,使其浮动起来,
    jQuery(form).css('top', '-1200px');
    jQuery(form).css('left', '-1200px');
    jQuery(form).appendTo('body'); //把动态form插入到body中

    var fd = new FormData($('#' + formId)[0]);
    for (var i = 0; i < curFileList.length; ++i) {
        fd.append('file[]', curFileList[i]);
    }
    return fd;
}


使用方法:
          var fd = createUploadForm("file" + row, { entityName: entityName, entityId: id, userId: userId, listName: rowData.ListName }, curFileList);
                $.ajax({
                    url: ClientUrl + '/UploadFile/Upload.html',
                    type: "post",
                    data: fd,
                    dataType: "json",
                    processData: false,
                    contentType: false,
                    success: function (data) {
                        $('#trackRecordTable').bootstrapTable('hideLoading');
                        $('#trackRecordTable').bootstrapTable('refresh');
                        alert(data.msg);
                    },
                    error: function (data) {
                        $('#trackRecordTable').bootstrapTable('hideLoading');

                        var result = eval('(' + data.responseText + ')');
                        alert(result.msg);
                    }
                });
  

 

posted @ 2019-01-05 15:58  Tk、  阅读(2745)  评论(0编辑  收藏  举报