jQuery $ .post将图像文件发送到servlet [英] jQuery $.post sending image file to servlet
问题描述
我有javaee
项目.我想通过ajax将图像文件发送到我的servlet.
Ajax没有将图像文件发送到我的Java类.但是它正在发送textarea值.
这是我的表格
I have javaee
project. I want to send image file to my servlet via ajax.
Ajax not sending image file to my java class. But it is sending textarea value.
Here is my form
<form enctype="multipart/form-data" beanclass="ActionBean">
<input type="file" id="uploadFile" name="newAttachment"/>
<textarea name="name" id="name" rows="2" cols="30"></textarea>
<s:submit value="Edit" name="saveOfferInfo" onclick="return edit(this);" />
JavaScript函数:
JavaScript function:
function edit(button) {
var form = button.form;
var params = $(form).serializeArray();
params.push({name: '_eventName', value: button.name});
$.post(form.action, params, function (data) {
alert("success");
});
推荐答案
查看 $.serializeArray()
,具体说来
Looking at the doc of $.serializeArray()
, it specifically says that
文件选择元素中的数据未序列化.
Data from file select elements is not serialized.
不幸的是,在AJAX中上传文件并不是那么简单.在此处中有使用纯JQuery的详细教程.要点是您需要:
Unfortunately, uploading file in AJAX isn't as straight forward. There is a detailed tutorial here using straight-up JQuery. The gist of it is that you need to:
- Bind the file input to a
change
event handler, - Gather all the form data in a FormData object,
- Then POST the form data using the
$.ajax
function.
工作太多?
或者,如果您不介意在代码中包含插件,则可以使用以下选项:
Alternately, if you don't mind including plugins in your codes, here are some options:
- jQuery-Ajax-File-Upload
- jquery-form
或者如Rohan所指出的那样,如果您使用的是HTML5,则可以浏览 FileReader API .
Or as Rohan pointed out, if you are using HTML5, you can explore the FileReader API.
这篇关于jQuery $ .post将图像文件发送到servlet的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!