[英]jQuery $.post sending image file to servlet
I have javaee
project. 我有javaee
项目。 I want to send image file to my servlet via ajax. 我想通过ajax将图像文件发送到我的servlet。 Ajax not sending image file to my java class. Ajax没有将图像文件发送到我的Java类。 But it is sending textarea value. 但是它正在发送textarea值。 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 function: JavaScript函数:
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");
});
File upload is not possible using AJAX, check for further details 无法使用AJAX上传文件,请查看更多详细信息
First of all I have to say that to create a pure AJAX file upload system is not possible because of security limitations of JavaScript. 首先,我不得不说,由于JavaScript的安全性限制,无法创建纯AJAX文件上传系统。 All of the Ajax upload systems I know use some third party tool/package or only mimics the AJAX feeling. 我知道所有的Ajax上传系统都使用某些第三方工具/程序包,或仅模仿AJAX的感觉。 Even so it makes file upload process a bit nicer. 即使如此,它也使文件上传过程变得更好。 In the next section I will present you a solution which imitates the AJAX process, but uses a normal upload process and iFrames. 在下一节中,我将向您介绍一个模仿AJAX流程,但使用常规上载流程和iFrame的解决方案。
The concept: 这个概念:
If you don't bother about older browser versions and want to code for the latest browsers then you can use FileReader API See Using HTML5 file uploads with AJAX and jQuery 如果您不用担心较旧的浏览器版本,并且想为最新的浏览器编写代码,则可以使用FileReader API。请参阅使用AJAX和jQuery使用HTML5文件上传
Looking at the doc of $.serializeArray()
, it specifically says that 查看$.serializeArray()
的文档,它具体说
Data from file select elements is not serialized. 来自文件选择元素的数据未序列化。
Unfortunately, uploading file in AJAX isn't as straight forward. 不幸的是,用AJAX上传文件并不是那么简单。 There is a detailed tutorial here using straight-up JQuery. 有一个详细的教程这里使用直线上升的JQuery。 The gist of it is that you need to: 要点是您需要:
change
event handler, 将文件输入绑定到change
事件处理程序, $.ajax
function. 然后使用$.ajax
函数发布表单数据。 Too much work? 太多的工作?
Alternately, if you don't mind including plugins in your codes, here are some options: 或者,如果您不介意在代码中包含插件,则可以使用以下选项:
Or as Rohan pointed out, if you are using HTML5, you can explore the FileReader API . 或者如Rohan所指出的那样,如果您使用的是HTML5,则可以探索FileReader API 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.