【问题标题】:Send image and additional informtion with AJAX to Servlet使用 AJAX 向 Servlet 发送图像和附加信息
【发布时间】:2015-02-06 14:29:26
【问题描述】:

你好,

我需要将图像从 <input type="file"> 元素发送到 servlet。 目前正在使用ajax

var files;
$("input[type='file']").on("change",function(e) {
        files = e.target.files;
        $("#Submit-Button").prop({"disabled":false});
});

$("#Submit-Button").on("click", function(){

        var data = new FormData();
        $.each(files, function(key, value){
            data.append(key, value);
        });

        $.ajax({
            url: "UploadServlet",
            type : "POST",
            data: data,
            cache: false,
            dataType: JSON,
            processData : false,
            contentType: false,
            success: function(data, textStatus, jqXHR){
                //SUCCESS
            },
            error: function(jqXHR, textStatus, errorThrown){
                    //ERROR
            }
        });
    })
});

这是有效的,我的 servlet 正在接收文件。

但是我想向 servlet 发送一些附加信息。

我试过(在js ajax方法中)

data : {data: data, userID : userID, username: username},

和(在 java servlet 中)

String Filename = request.getParameter("uid") + request.getParameter("username")+".png";
Collection<Part> Parts = request.getParts();

这显然是行不通的。

现在我想不出任何可以解决我的问题的方法。

【问题讨论】:

    标签: java javascript jquery ajax servlets


    【解决方案1】:

    添加文件的方式与添加任何其他数据的方式相同。

    ...
    data.append('userID', userID);
    data.append('username', username);
    ...
        $.ajax({
    ...
            data: data,
    ...
        });
    

    FormData.append

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-11-19
      • 1970-01-01
      • 2021-10-03
      • 1970-01-01
      • 2015-05-02
      • 2013-08-25
      • 1970-01-01
      相关资源
      最近更新 更多