【问题标题】:Jquery Webcam Plugin upload image to server using javaJquery Webcam Plugin使用java将图像上传到服务器
【发布时间】:2025-12-25 09:55:06
【问题描述】:

我想知道是否有一种方法可以使用 java 将图像上传到服务器。我正在使用 jquery 网络摄像头插件,他们有一个脚本可以执行此操作,但是我没有使用 php,我使用的是 SpringMVC (java)。

我不确定是否有办法配置 SpringMVC 项目以同时使用 php 和 java。这是我到目前为止所拥有的:

代码

var pos = 0, ctx = null, saveCB, image = [];
    var canvas = document.createElement('canvas');
    canvas.setAttribute('width', 320);
    canvas.setAttribute('height', 240);
    ctx = canvas.getContext('2d');
    image = ctx.getImageData(0, 0, 320, 240);

var saveCB = function (data) {
    var col = data.split(';');
    var img = image;
    for (var i = 0; i < 320; i++) {
        var tmp = parseInt(col[i]);
        img.data[pos + 0] = (tmp >> 16) & 0xff;
        img.data[pos + 1] = (tmp >> 8) & 0xff;
        img.data[pos + 2] = tmp & 0xff;
        img.data[pos + 3] = 0xff;
        pos += 4;
    }

    if (pos >= 4 * 320 * 240) {
        ctx.putImageData(img, 0, 0);
        foto = canvas.toDataURL("image/png");
        $("#photo").val(foto);
        pos = 0;
    }
};

$(document).ready(function(){

document.createElement("canvas");

$("#canvas").hide();

$("#camera").webcam({
        width: 320,
        height: 240,
        useMicrophone: false,
        mode: "callback",
        swffile: "resources/swf/jscam_canvas_only.swf",
        quality:85,

        onSave: saveCB,
        onCapture: function () {
            $("#camera").hide();
            webcam.save(//need a java function to upload to server );
            $("#canvas").show();                 

        },

        debug: function (type, string) {
            $("#status").html(type + ": " + string);
        }

}); 



$('#upload').click(function () {
    webcam.capture(); 
    return false;
});

$('#retake').click(function () {
    $("#canvas").hide();
    $("#camera").show();
    return false;
});


window.addEventListener("load", function() {

    var canvas = document.getElementById("canvas");

    if (canvas.getContext) {
        ctx = document.getElementById("canvas").getContext("2d");
        ctx.clearRect(0, 0, 320, 240);
        image = ctx.getImageData(0, 0, 320, 240);

    }

    }, false);

【问题讨论】:

    标签: java jquery html jsp spring-mvc


    【解决方案1】:

    将图像绘制到画布后 使用canvas.toDataURL() - 返回图片的base64编码数据作为请求参数

    然后在后端,使用Base64.decodeBase64(String data)将编码后的数据解码为字节数组:

    //@RequestParam data
    
    //remove mimeType declaration in the data string first
    
    String byteStr = data.split(",")[1];
    
    
    //get the byte array of the data
    
    byte[] bytes = Base64.decodeBase64(byteStr);
    

    【讨论】: