【问题标题】:How to download and then upload image with AngularJS如何使用 AngularJS 下载然后上传图像
【发布时间】:2016-07-09 14:07:17
【问题描述】:

我有一个 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
}

扫描仪的本地网络服务器可以通过如下链接访问扫描的图像: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:在未实现的对象上调用了“附加” 接口表单数据。

值 = jQuery.isFunction( 值 ) ?价值():(价值==空?“”: 值);

【问题讨论】:

  • 如果图像可以通过您提到的 URL 获得,为什么不在服务器本身处理上传部分。为什么要带角度。您可以只传递参数,说明什么 URL 将提供图像以及您需要的任何其他参数。在您的 saveImage 函数中,uploadong 可以使用图像上传 API 完成。这有意义吗?
  • @CoderJohn:实际上,REST Web 服务将在另一台服务器上运行,这就是为什么我无法在服务器端进行上传。

标签: javascript jquery angularjs image-uploading image-upload


【解决方案1】:

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

processData: false,
contentType: false,

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-10-20
    • 2017-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-05-20
    相关资源
    最近更新 更多