我需要支持如何上传一个新的图像文件使用聚合物和Java ..。我创建了一个包含两个字段的html表单:一个文件输入和一个简单的文本字段。我想把这些值放在我的ajax调用使用web组件铁-ajax在谷歌聚合物.实际上,我创建了一个代码片段,但是我不能将我的file...it作为空值发送,我不知道我做错了什么.
这是我的html表单:
<form method="post" enctype="multipart/form-data" modelAttribute="userInfo">
<paper-input type="file" id="txtFilePath" label="File path"></paper-input>
<paper-input id="firstname" name="firstname" label="Nome"></paper-input>
<paper-button id="btnSaveInfoProfile" on-tap="saveInfoProfile">Save</paper-button>
</form>
<iron-ajax id="ajaxSaveInfoProfile" method="POST" url="/updateInfoProfile" handle-as="json" on-response="responseUpdateInfoProfile" debounce-duration="0"></iron-ajax>
这是我的聚合物剧本:
...
saveInfoProfile: function()
{
this.$.ajaxSaveInfoProfile.params =
{
"imageProfile": this.$.imageProfile,
"firstName": this.$.firstname
};
this.$.ajaxSaveInfoProfile.generateRequest();
}
...
最后,这是我的Spring控制器:
@RequestMapping(value="/updateInfoProfile", method = RequestMethod.POST)
public @ResponseBody ReturnCode updateInfoProfile(@ModelAttribute("userInfo") UserInfoForm form, BindingResult result, HttpServletRequest request)
{
//...
}
当我选择我的文件并调用javascript方法时,html页面中的"imageProfile“值似乎没有定义.
我该怎么解决呢?我做错什么了?
谢谢!
发布于 2015-12-16 23:52:42
在服务器端,我使用php,但我希望能帮助您解决这个问题的客户端。iron-ajax
还不支持enctype="multipart/form-data"
,但是您可以使用javascript的FormData();
来处理它。您可以创建一个函数,该函数将文件转换为格式数据,然后将其附加到iron-ajax
的主体中。
Polymer({
......
convertFileInputToFormData: function(){
regexp = /^[^[\]]+/;
var fileInput = $('input[type="file"]');
var fileInputName = regexp.exec( fileInput.attr('name') );
// make files available
var data = new FormData();
jQuery.each($(fileInput)[0].files, function(i, file) {
data.append(fileInputName+'['+i+']', file);
});
return data;
},
.......
然后,您可以从预提交函数中调用它,如下所示
formPreSubmit: function(event){
var form = document.getElementById('Form');
// here you convert to formData calling our function
var data = this.convertFileInputToFormData();
form.request.method = "post";
// set undefined to prevent default json content type
form.request.contentType = undefined;
// here you append your formData to the iron-ajax body
form.request.body = data;
form.request.url = "http://your.api/url"
form.request.debounceDuration = 300;
},
默认情况下,form.request.contentType = undefined;
将iron-ajax
将内容类型设置为json。
我知道您不使用php,但是为了获得完整的想法,在php文件中您必须获得这样的数据。
if (isset($_FILES['file']['name'][0])) {
$file = $_FILES['file']['name'][0];
$type = $_FILES['file']['type'][0];
// here yor upload methods
}
$_FILES['file']['name'][0]
是因为它们可以处理图像数组。
我希望这能对你有所帮助,并为我糟糕的英语感到遗憾。
https://stackoverflow.com/questions/34302119
复制相似问题