如何使用AngularJS下载并上传图像

How to download and then upload image with AngularJS

本文关键字:图像 下载 何使用 AngularJS      更新时间:2023-09-26

我有一个Angularjs 1.5.0 web应用程序,它应该与我开发的基于REST的web服务通信(使用dropwizard&jersey),并测试了它的完美工作。

REST web服务方法如下:

@POST
@Path("/saveImage")
public Response saveImage(
    @FormDataParam("imagefile") InputStream uploadedInputStream,
    @FormDataParam("imagefile") FormDataContentDisposition fileDetail) {
    // save image on server's file system and return OK
}

扫描仪的本地web服务器可以通过以下链接向我提供扫描的图像:http://localhost:9980/thumb/random-generated-guid.jpg

在我的angularjs代码中,我想将上面的链接提供的图像发送到我的REST服务。

有人知道怎么做吗

我先尝试将图像保存为blob,然后将其发送到web服务。我可以使用javascript的XMLHttpRequest保存图像,但发送总是失败。将图像保存为Blob的代码:

var xhr = new XMLHttpRequest();
xhr.open('GET', imageAddress, true);
xhr.responseType = 'blob';
var imageData = null;
xhr.onload = function(e) {
    if (this.readyState === 4 && this.status === 200) {
        // get binary data as a response
        imageData = this.response;
        var gatewayResponse = sendToGateway(imageData);
    }
};

发送blob数据的代码:

var sendToGateway = function(imageDataBlob) {
        var formdata = new FormData();
        formdata.append('imagefile', imageDataBlob)
        $.ajax({
            url: 'http://localhost/eval/saveImage',
            method: 'POST',
            contentType: 'multipart/form-data; charset=UTF-8',
            data: formdata,
            dataType: 'json',
        })
        .done(function(response) {
            $log.info("**************** response = " + response);
            alert("response:'n" + response);
        })
        .fail(function(jqXHR, textStatus, errorThrown) {
            $log.error("!!!! FAIL !!!!!!!!!");
            alert("FAIL !!!!!!!");
        })
        .always(function(){
            $rootScope.scannerInactive = false;
            doStartPreviewUpdate();
        });
    };

实际上,问题是当sendToGateway(imageData)被调用,我得到错误:

TypeError:在未实现的对象上调用了"append"接口FormData。

value=jQuery.isFunction(value)?value():(value==null?":值);

oops,我发现了问题。我应该在$.ajax()调用中添加以下指令。

processData: false,
contentType: false,