jQuery $ .post将图像文件发送到servlet [英] jQuery $.post sending image file to servlet

查看:82
本文介绍了jQuery $ .post将图像文件发送到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:

  1. 将文件输入绑定到change事件处理程序,
  2. FormData 对象中收集所有表单数据,
  3. 然后使用 $.ajax 函数发布表单数据.
  1. Bind the file input to a change event handler,
  2. Gather all the form data in a FormData object,
  3. Then POST the form data using the $.ajax function.

工作太多?

或者,如果您不介意在代码中包含插件,则可以使用以下选项:

Alternately, if you don't mind including plugins in your codes, here are some options:

  1. jQuery-Ajax-File-Up
  2. jquery形式
  1. jQuery-Ajax-File-Upload
  2. 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆