交换多个上传的输入文件

时间:2016-02-08 02:07:45

标签: javascript jquery html ajax jsp

我尝试在我的网络应用程序中创建一些文件上传功能。

我允许在服务器上最多上传三个文件,但在尝试删除文件时仍然存在交换文件问题。

首先我的代码如下:

request.jsp

HTML方面

<tr>
    <td class="tbContent" rowspan="3" valign="middle" style="border-style: hidden solid solid solid;">Attachment</td>
    <td class="tbContent" valign="middle" style="border-style: hidden solid solid solid;">
    <input type="file" id="docFile1" name="docFile1" size="50" style="width:85px;"/></td>
    <td class="tbContent" valign="middle" style="border-style: hidden solid solid hidden;">
    <input type="text" readonly="readonly" id="test1" class="test1" style="border:0;"/></td>
    <td class="tbContent" valign="middle" style="border-style: hidden solid solid hidden;">
    <button type="button" id="clearDocFile1" style="display:none;">Delete</button></td>
</tr>
<tr>
    <td class="tbContent" valign="middle" style="border-style: hidden solid hidden solid;">
    <input type="file" id="docFile2" name="docFile2" size="50" style="display:none; width:85px;"/></td>
    <td class="tbContent" valign="middle" style="border-style: hidden solid solid hidden;">
    <input type="text" readonly="readonly" id="test2" class="test2" style="border:0;"/></td>
    <td class="tbContent" valign="middle" style="border-style: hidden solid solid hidden;">
    <button type="button" id="clearDocFile2" style="display:none;">Delete</button></td>
</tr>
<tr>
    <td class="tbContent" valign="middle" style="border-style: hidden solid solid solid;">
    <input type="file" id="docFile3" name="docFile3" size="50" style="display:none; width:85px;"/></td>
    <td class="tbContent" valign="middle" style="border-style: hidden solid solid hidden;">
    <input type="text" readonly="readonly" id="test3" class="test3" style="border:0;"/></td>
    <td class="tbContent" valign="middle" style="border-style: hidden solid solid hidden;">
    <button type="button" id="clearDocFile3" style="display:none;">Delete</button></td>                 
</tr>

JavaScript方面

var docInput = document.getElementById('docFile1');
docInput.addEventListener("change", getDocumentFileInfo1, false);

function getDocumentFileInfo1() {
    var fileList1 = this.files;
    oFReader1 = new FileReader();
    oFReader1.name = fileList1[0].name;
    getGetOne = oFReader1.name;
    oFReader1.size = fileList1[0].size;
    console.log("name outside:", oFReader1.name);
    console.log("size outside:", oFReader1.size);
    $("#fileName1").val(oFReader1.name);
    $('#test1').val(oFReader1.name);
    if (oFReader1 != ""){
        $("#docFile2").show();
        $("#clearDocFile1").show();
        $("#docFile1").hide();
    } else {
        $("#docFile2").hide();
        $("#clearDocFile1").hide();
        $("#docFile1").show();
    }; 
};

var docInput2 = document.getElementById('docFile2');
docInput2.addEventListener("change", getDocumentFileInfo2, false);

function getDocumentFileInfo2() {
    var fileList2 = this.files;
    oFReader2 = new FileReader();
    oFReader2.name = fileList2[0].name;
    getGetTwo = oFReader2.name;
    oFReader2.size = fileList2[0].size;
    console.log("name outside:", oFReader2.name);
    console.log("size outside:", oFReader2.size);
    $("#fileName2").val(oFReader2.name);
    $('#test2').val(oFReader2.name);

    if (oFReader2 != ""){
        $("#docFile3").show();
        $("#clearDocFile2").show();
        $("#clearDocFile1").hide();
        $("#docFile2").hide();
    } else if (oFReader2 = undefined) {
        $("#docFile3").hide();
        $("#clearDocFile2").hide();
        $("#clearDocFile1").show();
        $("#docFile1").show();
    };

    if (getGetOne == oFReader2.name) {
        alert("You cannot attach two same files");
        $("#docFile2").val("");
        $("#fileName2").val("");
        $("#test2").val("");
        $("#clearDocFile1").show();
        $("#clearDocFile2").hide();
        $("#docFile2").show();
        $("#docFile3").hide();
    };
};

var docInput3 = document.getElementById('docFile3');
docInput3.addEventListener("change", getDocumentFileInfo3, false);

function getDocumentFileInfo3() {
    var fileList3 = this.files;
    oFReader3 = new FileReader();
    oFReader3.name = fileList3[0].name;
    getGetThree = oFReader3.name;
    oFReader3.size = fileList3[0].size;
    console.log("name outside:", oFReader3.name);
    console.log("size outside:", oFReader3.size);
    $("#fileName3").val(oFReader3.name);
    $('#test3').val(oFReader3.name);

    if (oFReader3 != ""){
        $("#clearDocFile1").hide();
        $("#clearDocFile2").hide();
        $("#clearDocFile3").show();
        $("#docFile3").hide();
    } else {
        $("#clearDocFile1").show();
        $("#clearDocFile2").show();
        $("#clearDocFile3").hide();
        $("#docFile3").show();
    };

    if (getGetOne == oFReader3.name || getGetTwo == oFReader3.name) {
        alert("You cannot attach two same files");
        $("#docFile3").val("");
        $("#fileName3").val("");
        $("#test3").val("");
        $("#clearDocFile2").show();
        $("#clearDocFile3").hide();
        $("#docFile3").show();
    };
};

(SKIP)

$('#formAddNewDoc').ajaxForm();
    var options = {
        url:"<c:url value='/app/addDocument/files'/>",
        type: 'post',
        dataType: 'json',
        contentType : "application/json",
        beforeSubmit: function(arr, $form, options){
        options.context = $form;
    },
    beforeSend: function(e) {
        e.setRequestHeader('token', 'euejrhzkehrkherkhekr');
    },
    complete: function (data){
        var file_name = data.responseText;
        console.log(file_name);

        var jsonTwo = {
            fileName1 : $("#fileName1").val(),
            fileName2 : $("#fileName2").val(),
            fileName3 : $("#fileName3").val(),
            documentId : $("#documentId").val()
        };
        $.ajax({
            contentType : "application/json",
            dataType : 'json',
            type : "POST",
            url : "<c:url value='/app/addDocument/fileInfo'/>",
            data : JSON.stringify(jsonTwo),
            success : function(jsonTwo) {
                if (status){
                    toastMessage("Add File Info", "Added File Info Successfully", CONSTANT.TOASTICONSUCCESS, CONSTANT.TOASTBOTTOMCENTERPOS, "");
                } else {
                    toastMessage("Add File Info", "Error Occurred", CONSTANT.TOASTICONERROR, CONSTANT.TOASTBOTTOMCENTERPOS, "");
                }
            },

ApprovalController.java

@RequestMapping(value="/addDocument/fileInfo", method=RequestMethod.POST)
@ResponseBody
public boolean addDocumentFile(@RequestBody DocumentFile documentFile) {
    try {
        //String primary = autoPrimaryKeyService.autoNumberByTable("document_file", "fileId", AutoPrimaryKey.FILE);
        String anotherOne = autoPrimaryKeyService.autoNumberByTable("document", "documentId", AutoPrimaryKey.APPROVAL);
        //documentFile.setFileId(primary);
        documentFile.setDocumentId(anotherOne);
        documentFileService.addDocumentFile(documentFile);

        logger.info("Added File Successfully");
        return true;
    } catch (Exception e) {
        logger.error("Added File", e.getMessage());
        return false;
    }
}

@RequestMapping(value="/addDocument/files")
@ResponseBody
public DocumentFile handleFileUpload(
        @RequestParam(value = "docFile1", required = false) MultipartFile docFile1,
        @RequestParam(value = "docFile2", required = false) MultipartFile docFile2,
        @RequestParam(value = "docFile3", required = false) MultipartFile docFile3) {

    String primary = autoPrimaryKeyService.autoNumberByTable("document", "documentId", AutoPrimaryKey.APPROVAL);
    File file = new File(ViewMapper.UPLOAD_DOC_PATH + "/" + primary);

    String temp1 = ViewMapper.UPLOAD_DOC_PATH + "/" + primary + "/" + docFile1.getOriginalFilename();
    String file_name1 = docFile1.getOriginalFilename();

    DocumentFile fileString = new DocumentFile();

    if (!file.mkdir()){
        file.mkdir();
    }

    if(!docFile1.isEmpty()){
        try {
            byte[] bytes = docFile1.getBytes();
            BufferedOutputStream stream = new BufferedOutputStream(new FileOutputStream(new File(temp1)));
            stream.write(bytes);
            stream.close();
            fileString.setFileName1(file_name1);

            if(!docFile2.isEmpty()){
                String temp2 = ViewMapper.UPLOAD_DOC_PATH + "/" + primary + "/" + docFile2.getOriginalFilename();
                String file_name2 = docFile2.getOriginalFilename();

                byte[] bytes2 = docFile2.getBytes();
                BufferedOutputStream stream2 = new BufferedOutputStream(new FileOutputStream(new File(temp2)));
                stream2.write(bytes2);
                stream2.close();
                fileString.setFileName2(file_name2);
            }

            if(!docFile3.isEmpty()){
                String temp3 = ViewMapper.UPLOAD_DOC_PATH + "/" + primary + "/" + docFile3.getOriginalFilename();
                String file_name3 = docFile3.getOriginalFilename();

                byte[] bytes3 = docFile3.getBytes();
                BufferedOutputStream stream3 = new BufferedOutputStream(new FileOutputStream(new File(temp3)));
                stream3.write(bytes3);
                stream3.close();
                fileString.setFileName3(file_name3);
            }

            DocumentFile document = new DocumentFile();
            documentFileService.addDocumentFile(document);

            logger.info("Uploaded File Successfully.");
            return fileString;
        } catch(Exception e) {
            logger.error("Uploaded File.", e.getMessage());
            return null;
        }
    } else {
        logger.info("No File.");
        return null;
    }       
}

目前,当您首次启动应用程序时,用户会看到如下屏幕:

enter image description here

然后,如果用户选择它,将会改变这些

enter image description here

enter image description here

enter image description here

用户只能删除最后添加的项目,并在删除时选择其他文件。

我想让它像三个项目一样有效,如果第二个项目被删除,那么第三个项目成为第二个项目,第三个项目变为空白。

之前,我尝试过这样的事情:

jQuery.fn.swapWith = function(to) {
    return this.each(function() {
        var copy_to = $(to).clone(true);
        var copy_from = $(this).clone(true);
        $(to).replaceWith(copy_from);
        $(this).replaceWith(copy_to);
    });
};

$("#clearDocFile2").on('click', function(){
    var temTwo = $("#docFile2").val();
    var ttemTwo = $("#fileName2").val();
    var tttemTwo = $("#test2").val();

    var temThree = $("#docFile3").val();
    var ttemThree = $("#fileName3").val();
    var tttemThree = $("#test3").val();

    if (temThree == ""){
        $("#docFile2").val("");
        $("#fileName2").val("");
        $("#test2").val("");
        $("#clearDocFile1").show();
        $("#clearDocFile2").hide();
        $("#clearDocFile3").hide();
        $("#docFile3").hide();
        $("#docFile2").show();
    } else {
        $("#fileName2").swapWith("#fileName3");
        $("#test2").swapWith("#test3");

        $("#clearDocFile1").show();
        $("#clearDocFile2").show();
        $("#clearDocFile3").hide();
        $("#docFile3").show();
        $("#docFile2").hide();
    }
});

但是当我试图删除三个中的第二个项目时,这只会交换名称(第三个项目的名称也不是空的)并且所选文件仍然相同,所以当我提交表单时,第二个和第三项没有上传。

提前谢谢。

1 个答案:

答案 0 :(得分:0)

您应该只删除整行,然后添加一个新行,而不是尝试交换值。

正如我所知道的那样,在文件输入上没有安全的方法(就这一点而言总是有效)来做这样的交换值,因为这将包括通过代码读取和设置文件URL,这将是导致一些严重的安全问题。由于某些浏览器的安全问题,甚至文件路径有时也会被混淆,不存在。

枚举字段名,变量,几乎每次都是坏符号。 我对JSP没有任何经验;对于PHP,可以将所有三个字段命名为file[],PHP将为我提供一个名为file的值数组;不知道JSP中有类似的东西。

在快速谷歌搜索中,我发现这个示例http://www.codejava.net/java-ee/servlet/java-multiple-files-upload-example用于似乎没有任何字段名称的JSP;仍然无法判断代码有多好。