开发细节:上传表单带文件

这段代码展示了前端如何使用JavaScript处理文件上传,包括监听文件选择、渲染文件列表和删除文件的功能。当用户选择文件后,文件信息会被显示在表格中,并标记为未上传状态。点击保存按钮时,会通过Ajax将文件信息和表单数据一起发送到后台。后台接收到请求后,会对数据进行校验,如果校验通过则保存数据。代码中还包含了错误处理和保存成功的提示信息。
摘要由CSDN通过智能技术生成
            <div style="padding-top:10px ">
                <hr style="z-index: -1;"/>
                <p style="position: relative;width: 65px;padding-left:5px;margin-top: -27px;margin-bottom: -10px;z-index: 100; background-color:#f1f4f7">附件列表</p>
            </div>
            <div class="clearfix">
                <table class="commonTable mT10">
                    <thead>
                    <tr>
                        <th width="10%">序号</th>
                        <th>文件</th>
                        <th width="10%">状态</th>
                        <th width="10%">操作</th>
                    </tr>
                    </thead>
                    <tbody id="fileList" class="content-list">

                    </tbody>
                </table>
            </div>
$(document).ready(function () {
    var fileList = [];
    var fileCatcher = document.getElementById('entryHeadForm');
    var files = document.getElementById("attachment"), renderFileList;
    var fileListDisplay = document.getElementById('fileList'), sendFile;

    fileCatcher.addEventListener("submit", function (event) {
        event.preventDefault();
        //上传文件
        sendFile();
    });

    files.addEventListener("change", function (event) {
        fileList = [];
        for (var i = 0; i < files.files.length; i++) {
            fileList.push(files.files[i]);
        }
        renderFileList();
    });

    renderFileList = function () {
        fileListDisplay.innerHTML = '';
        fileList.forEach(function (file, index) {
            var fileDisplayEl = document.createElement("tr");

            // var tbody = " <tr>\n" +
            //     "<td>"+(index + 1)+"</td>\n" +
            //     "<td>"+file.name+"</td>\n" +
            //     "<td>"+"未上传"+"</td>\n" +
            //     "<td><a href=\"javascript:removeAttachment();\" class=\"ddBtn btnRed ml5\">\n" +
            //     "                                <i class=\"fa fa-save\"></i>删除</a></td>\n" +
            //     "</tr>"
            // $("#fileList").appendChild(tbody);

            fileDisplayEl.innerHTML = " <tr>\n" +
                "<td>"+(index + 1)+"</td>\n" +
                "<td>"+file.name+"</td>\n" +
                "<td>"+"未上传"+"</td>\n" +
                "<td><button onclick = 'removeAttachment(" + index + ")'  class='ddBtn btnRed ml5 '>删除</button></td>\n" +
                "</tr>";
            fileListDisplay.appendChild(fileDisplayEl);
        })
    };

})


//删除文件
function removeAttachment(index) {
    $("#fileList").find("tr").eq(index).hide();

    var fileList = $("#attachment").get(0).files;

    fileList[index].value = "";
    // var files = document.getElementById("attachment");
    // fileList.splice(index,1);

    // files.files[index];
    // var objFile = document.getElementById('attachment').value;
    console.log(fileList);
}
/**
 * 保存
 */
function saveAll(){
    $('#appType').removeAttr("disabled");
    var datas = {};
    datas.appAbnExpressVO = $("#entryHeadForm").serializeObject();

    var entryHeadIds = "";
    var obj = $(".ids");
    obj.each(function () {
        entryHeadIds += $(this).attr('id') + ",";
    });
    entryHeadIds = entryHeadIds.substr(entryHeadIds,entryHeadIds.length - 1);
    datas.entryHeadIds = entryHeadIds;

    var excelImportSave = art.dialog.data("excelImportSave");
    if(excelImportSave == null || excelImportSave == undefined || excelImportSave == ''){
        datas.ehsEntryHeadVOS = null;
    }else{
        datas.ehsEntryHeadVOS = excelImportSave;
    }

    var fileList = $("#attachment").get(0).files;//获取指定ID的文件信息
    var formData = new FormData();//创建FormData对象,将所需的信息封装到内部,以键值对的方式
    for (var i = 0, file; file = fileList[i]; i++) {
        if (file.value == "") {
            // console.log("attachment"+file.name);
            continue;
        }
        formData.append('files', file, file.name); // 文件名称,文件对象
    }
    formData.append("appAbnExpressSaveVOJson",JSON.stringify(datas))

    $.pikaQajax({
        url: "/pending/save-apply-data",
        data: formData,
        processData: false,
        contentType: false,
        type: "post",
        // contentType: 'application/json',
        success: function (data) {
            if (data.status === 200) {
                var entryHeadIds = "";
                art.dialog.data("entryHeadIds",entryHeadIds);
                art.dialog({
                    title: '提示', content: '保存成功', ok: function () {
                        art.dialog.data("excelImportSave","");
                        window.location.href="/applied/apply-list-query";
                    }
                });
            }else {
                $.alert(data.msg);
            }
        }
    });
}

后端:

@RequestMapping("/save-apply-data")
    @ResponseBody
    public ApiResponses<Void> saveApplyData(@RequestParam(value = "appAbnExpressSaveVOJson") String appAbnExpressSaveVOJson,@RequestParam(value = "files") MultipartFile[] files)throws Exception{
        appAbnExpressSaveVOJson = StringEscapeUtils.unescapeHtml(appAbnExpressSaveVOJson);
        ObjectMapper mapper = new ObjectMapper();
        AppAbnExpressSaveVO appAbnExpressSaveVO = mapper.readValue(appAbnExpressSaveVOJson, AppAbnExpressSaveVO.class);

//数据和文件校验
    .
    .
    .
}
 BindingResult result = new BindException(appAbnExpressSaveVO, "appAbnExpressVO");
        springValidator.validate(appAbnExpressSaveVO.getAppAbnExpressVO(),result,AppAbnExpressVO.Save.class);

        if (result.hasErrors()) {
            String errorMessage = "参数错误或不完整:<br/>";
            List<ObjectError> allErrors = result.getAllErrors();
            for (ObjectError obj : allErrors) {
                errorMessage += obj.getDefaultMessage() + "<br/>";
            }
            ApiAssert.isNull(ErrorCodeEnum.BAD_REQUEST.convert(errorMessage));
        }

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值