将 base64 格式的图像发送到 Java 网络服务器,转换并保存

Sending image in base64 to Java webserver, convert and save it

我有一个网站有持续的网络摄像头流,应该将视频流的快照发送到我自己的 Java 网络服务器。快照生成和显示功能在网站上完美运行。我想将带有 jQuery AJAX POST 请求的快照发送到我的网络服务器,如下所示:

$.ajax({
    type: 'POST',
    url: servicePath + "upload",
    contentType: 'multipart/form-data',
    xhrFields: {withCredentials: false},
    headers: {},
    data: hidden_canvas.toDataURL('image/png'),
    success: function(data, status, xhttp) {
        alert(data);
    },
    error: function() {
        alert("Error uploading snapshot file to server!");
    }
}); 

正如我提到的,显示 <img>src 属性中插入的 hidden_canvas.toDataURL('image/png') 效果完美,因此绝对有效。

我的 服务 在网络服务器上看起来如下:

@POST
@Path("/upload")
@Consumes(MediaType.MULTIPART_FORM_DATA)
public Response uploadPicture(byte[] imageBytes) {

    String uploadedFileLocation = UPLOAD_FOLDER + "test.png";

    try {
        OutputStream out = new FileOutputStream(new File(uploadedFileLocation));
        out.write(imageBytes);
        out.flush();
        out.close();
    } catch (IOException e) {       
        return Response.status(500).entity("Can not save file<br>" + e.toString()).build();
    }

    return Response.status(200).entity("success").build();
}

Test.png创建成功,但不是有效的png,打开后根本不显示。服务器上的文件如下所示:

我错过了什么?是否有其他方法来处理图像?


这是我的 takeSnapshot 方法。如果没有 toDataURL(),我如何发送文件?那么在服务器端我必须期待什么参数?

function generateSnapshot() {
   var video = document.querySelector('#camera-stream');
   var hidden_canvas = document.querySelector('#canvas');
   var context = hidden_canvas.getContext('2d');

   var width = video.videoWidth;
   var height = video.videoHeight;

   if (width && height) {
       hidden_canvas.width = width;
       hidden_canvas.height = height;

       // Make a copy of the current frame in the video on the canvas.
       context.drawImage(video, 0, 0, width, height);

       // Turn the canvas image into a dataURL that can be used as a src for our photo.
       return hidden_canvas.toDataURL('image/png');
   }
}

我终于可以让它工作了。 KayamantoBlob 建议让我走上了正确的轨道。但是我无法按预期发送 blob,我不得不将其放入 FormData 中,因此不得不调整我的网络服务。解决方案如下所示:

网站Java脚本代码:

hidden_canvas.toBlob(function(blob) {
    var fd = new FormData();
    fd.append('fileName', 'testBlob.png');
    fd.append('data', blob);
    sendAJAXFileUploadRequest(fd);
},'image/png');

function sendAJAXFileUploadRequest(formData) {
   $.ajax({
       type: 'POST',
       url: servicePath + "upload",
       xhrFields: {withCredentials: false},
       headers: {},
       data: formData,
       processData: false,
       contentType: false,
       success: function(data, status, xhttp) {
           alert(data);
       },
       error: function() {
           alert("Error uploading snapshot file to server!");
       }
   });          
}

Java 网络服务:

@POST
@Path("/upload")
@Consumes(MediaType.MULTIPART_FORM_DATA)
public Response uploadPicture(@FormDataParam("data") byte[] imageBytes, @FormDataParam("fileName") String fileName) {

    String uploadedFileLocation = UPLOAD_FOLDER + fileName;

    try {
        OutputStream out = new FileOutputStream(new File(uploadedFileLocation));
        out.write(imageBytes);
        out.flush();
        out.close();
    } catch (IOException e) {       
        logger.severe("Can not save file (file location: " + uploadedFileLocation + ")");
        return Response.status(500).entity("Can not save file<br>" + e.toString()).build();
    }

    return Response.status(200).entity("success").build();
}