有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

javascript jQuery$。将图像文件发送到servlet后

我有一个javaee项目。我想通过ajax将图像文件发送到我的servlet。 Ajax没有将图像文件发送到我的java类。但它正在发送textarea值。 这是我的表格

<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 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");
});

共 (2) 个答案

  1. # 1 楼答案

    看看^{}的文件,它明确地说

    Data from file select elements is not serialized.

    不幸的是,用AJAX上传文件并不是那么简单。有一个详细的教程here使用直接的JQuery。要点是你需要:

    1. 将文件输入绑定到change事件处理程序
    2. FormData对象中收集所有表单数据
    3. 然后使用^{}函数发布表单数据

    工作太多

    或者,如果您不介意在代码中包含插件,以下是一些选项:

    1. jQuery-Ajax-File-Upload
    2. jquery-form

    或者正如Rohan指出的,如果你使用HTML5,你可以探索FileReader API

  2. # 2 楼答案

    使用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. All of the Ajax upload systems I know use some third party tool/package or only mimics the AJAX feeling. 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.

    这个概念:

    • 为文件上传创建一个简单的HTML表单
    • 将目标设置为在实际页面上但不可见的iFrame
    • 在表单提交上调用JavaScript函数以显示动画
    • PHP部分完成上传过程后,会隐藏动画

    Read more

    如果你不关心旧版本的浏览器,并且想为最新的浏览器编码,那么你可以使用FileReader API参见Using HTML5 file uploads with AJAX and jQuery