jquery - ColdFusion无法读取Ajax发送的FormData

标签 jquery ajax file-upload coldfusion jquery-file-upload

我正在创建一个文件上传组件,我可以 <cfinclude>到我的任何 CFM 页面上,该页面允许标准文件选择和拖放功能。

选择文件并提交表单时,没有问题,因为我的 ColdFusion 代码依赖于表单范围来检索文件。

为了使用拖放功能发送文件,我使用 jQuery 通过 Ajax 发送请求 FormData基于当前表单。

$form.on('submit', function(e) {
    e.preventDefault();

    // Get FormData based on form and append the dragged and dropped files 
    var ajaxData = new FormData($form.get(0));
    if (droppedFiles) {
        $.each(droppedFiles, function(i, file) {
            ajaxData.append($('input[type=file]').attr('name'), file);
        });
    }

    $.ajax({
        url: $form.attr('action'),
        type: $form.attr('method'),
        cache: false,
        contentType:false,
        processData: false,
        success: function(data) {
            if (data.SUCCESS) uploadSuccessful($form);
            else
            {
                console.error(data.ERROR);
            }
        },
        error: function(jqXHR, textStatus, errorThrown) {
            console.error('Error: File upload unsuccessful ' + errorThrown);
        },
        data: ajaxData,
        dataType: 'json',
        dataFilter: function(data, type){ 
            return data.substring(2, data.length); 
        }
    });
});

HTML:

<form class="file-upload-container" method="post" action="upload.cfm" enctype="multipart/form-data">
    <label class="file-upload-input">
        <i class="fa fa-upload" aria-hidden="true" style="font-size:5em;"></i><br/><br/>
        <input type="file" name="attachment" id="attachment" />
    </label>
    <div class="file-upload-controls">
        <input type="button" id="cancelUpload" value="Cancel" class="btn btn-green" />
        <input type="submit" id="upload" value="Upload" class="btn btn-green" />
    </div>
</form>

action <form>的是发布到我的upload.cfm页面。

我首先验证发布的表单是否包含名为“attachment”的元素:

<cfif structKeyExists(form, "attachment")>
    <!--- This always passes since I'm posting the form with the submit button --->
</cfif>

然后,我尝试检索文件名,以便可以与接受的文件类型进行比较、上传文件、重命名文件,并将条目插入数据库。我遇到问题的地方是当我尝试从发布的 FormData 获取文件名时对象(甚至整个文件的内容......)。

<cffunction name="GetTheFileName" access="public" returntype="string" output="false" >
    <cfargument name="fieldName" required="true" type="string" hint="Name of the Form field" />

    <cfset var tmpPartsArray = Form.getPartsArray() />

    <cfif IsDefined("tmpPartsArray")>
        <cfloop array="#tmpPartsArray#" index="local.tmpPart">
            <cfif local.tmpPart.isFile() AND local.tmpPart.getName() EQ arguments.fieldName> 
                <cfreturn LCase(local.tmpPart.getFileName()) />
            </cfif>
        </cfloop>
    </cfif>
    <cfreturn "" />
</cffunction>

线路Form.getPartsArray()返回一个数组,但数组中的值为空。 (例如,文件路径:'',文件名:'')

这让我相信 FormData无论 ajax 是否发布 FormData,其行为方式都与发布的实际表单不同。作为多部分/表单数据。

问题

  1. 为了阅读FormData,我错过了什么? ColdFusion 端的对象,以便检索文件名。

  2. Form范围如何有效利用发布FormData就好像它是一个实际的 <form>正在发布。

研究

这个source表明我可以使用Java的FileOutputStream读取文件。 (这不是一个理想的解决方案,因为我还允许典型的“选择文件”,它已经利用了表单范围)

最佳答案

我找到了一个解决方案,尽管不是我最初希望的解决方案。

根据我的观察,ColdFusion 对待 FormData 对象的方式与实际表单发布的方式不同。当表单范围不包含表单数据时,这一点很明显。

相反,我必须以不同的方式处理通过拖放功能发布的数据。

按照建议的上传文件 block 的方法 ( source ),我通过 ajax 请求了 upload.cfm 页面,其中 Content-Type 与要上传的文件的 MimeType 相匹配,并且实际上传使用java.io.FileOutputStream类将文件写入磁盘。

JavaScript + AJAX:

var droppedFiles; // Assuming droppedFiles was populated during the 'drop' event

// Get the Form and FormData (although FormData won't be used when files are Dragged  & Dropped)
var $form = $('.file-upload-container');
var ajaxData = new FormData($(form).get(0));

var dragged = false;                
var filesToBeUploaded = document.getElementById("attachment");  
var file = filesToBeUploaded.files[0]; 
if (droppedFiles){file = droppedFiles;dragged=true;}

$.ajax({
    url: $form.attr('action'),
    type: $form.attr('method'),
    cache: false,
    contentType: dragged ? file.type : false,
    processData: false,
    success: function(data) {
        if (data.SUCCESS) { // Do stuff }
        else
        {
            // Do stuff
            console.error(data.ERROR);
        }
    },
    error: function(jqXHR, textStatus, errorThrown) {
        console.error('Error: File upload unsuccessful ' + errorThrown);
    },
    data: dragged ? file : ajaxData,
    dataType: 'json',
    dataFilter: function(data, type){ 
        return data.substring(2, data.length); 
    },
    headers: { 'X_FILE_NAME': dragged ? file.name : "", 'X_CONTENT_TYPE': dragged ? file.type : "" }
});

冷聚变:

<cfset bUseFormData = false />

<cfset headerData = getHTTPRequestData().headers>
<cfif structKeyExists(headerData, "X_FILE_NAME") AND ("#headerData.X_FILE_NAME#" NEQ "")>
    <cfset bUseFormData = true />        
</cfif>

<cfif structKeyExists(form, "attachment") OR bUseFormData>

    <cfif bUseFormData>
        <cfset content = getHTTPRequestData().content>
        <cfset filePath = "#Application.AdminUploadPath#\" & "#headerData.X_CONTENT_TYPE#">
        <cfset fos = createObject("java", "java.io.FileOutputStream").init(filePath, true)>
        <cfset fos.write(content)>
        <cfset fos.close()>
    <cfelse>
        <cffile action="UPLOAD" filefield="form.attachment" destination="#Application.AdminUploadPath#">
    </cfif>

</cfif>

为了简单起见,我排除了验证文件扩展名、MimeType 和错误处理的代码。

关于jquery - ColdFusion无法读取Ajax发送的FormData,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49011881/

相关文章:

javascript - 如何在页面更新时执行jquery

php - 当包含特定文件扩展名时如何将类添加到超链接?

javascript - 使用jquery在多个html文件中搜索字符串

javascript - 使用 AJAX 发送密码时如何保护密码?

jquery - nyromodal ajax 表单/过滤器文档或完整示例?

javascript - 如何使用外部删除按钮删除文件 - Blueimp FileUploader UI

java - 从jsp上传文件

javascript - jQuery 切换 : Close all open li when another one is clicked

javascript - 页面刷新时未调用 Struts2 操作

php - 我想通过 Dreamweaver 将文件 uploader 添加到现有内容 uploader - 将 pdf 上传到特定文件夹,在数据库中生成 pdf 的 url