Because of a Flex bug uploading files in a secure environment ,我正在尝试用 javascript 来解决这个问题。
为此,我尝试在 javascript 中创建一个隐藏表单,向其中附加一个文件和一些 xml 元数据,然后以多部分表单帖子的形式将其发送到服务器。我的第一个想法是让它在 HTML 中工作,然后将此 javascript 代码移植到我的 Flex 项目中。
我的第一个问题是将文件附加到 JavaScript 中的隐藏表单。我在这里做错事了。我对 javascript 非常缺乏经验,所以如果有更好的方法来做到这一点,我很想学习。
这是我当前正在使用的代码。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>hidden form post demo</title>
</head>
<body>
<script>
//helper function to create the form
function getNewSubmitForm(){
var submitForm = document.createElement("FORM");
document.body.appendChild(submitForm);
submitForm.method = "POST";
submitForm.enctype = "multipart/form-data";
return submitForm;
}
//helper function to add elements to the form
function createNewFormElement(inputForm, inputType, elementName, elementValue) {
var inputElement = document.createElement("INPUT");
inputElement.name = elementName;
inputElement.type = inputType;
try {
inputElement.value = elementValue;
} catch(err) {
alert(err.description);
}
inputForm.appendChild(inputElement);
return inputElement;
}
//function that creates the form, adds some elements
//and then submits it
function createFormAndSubmit(){
var submitForm = getNewSubmitForm();
var selectedFileElement = document.getElementById("selectedFile");
var selectedFile = selectedFileElement.files[0];
createNewFormElement(submitForm, "HIDDEN", "xml", "my xml");
createNewFormElement(submitForm, "FILE", "selectedFile", selectedFile);
submitForm.action= "my url";
submitForm.submit();
}
</script>
<div id="docList">
<h2>Documentation List</h2>
<ul id="docs"></ul>
</div>
<input type="file" value="Click to create select file" id="selectedFile"/>
<input type="button" value="Click to create form and submit" onclick="createFormAndSubmit()"/>
</body>
</html>
你可以看到,我在 createNewFormElement
中有一个 try/catch block 。那里抛出异常,但消息显示“未定义”。
在 FireBug 中,我可以看到 elementValue
设置为 File 对象,因此我不太确定发生了什么。
最佳答案
出于安全原因,您无法设置input[type=file]
的value
属性。您当前的代码不需要 JavaScript,可以使用纯 HTML 编写:
<form method="post" enctype="multipart/form-data" action="myurl">
<input type="file" value="Click to create select file" name="selectedFile" />
<input type="hidden" name="xml" value="my xml" />
<input type="submit" value="Click to create form and submit" />
</form>
如果您愿意,可以通过将事件绑定(bind)到 onsubmit
处理程序来动态添加其他非文件表单元素。
<form ... onsubmit="addMoreinputs();" id="aForm">
...
<script>
function addMoreInputs(){
var form = document.getElementById("aForm");
// ...create and append extra elements.
// once the function has finished, the form will be submitted, because
// the input[type=submit] element has been clicked.
}
关于javascript - javascript中的隐藏表单文件POST,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7918445/