简体   繁体   中英

How to download and then upload image with AngularJS

I have an Angularjs 1.5.0 web application which should communicate with a REST-based web service that I had developed (using dropwizard & jersey) and tested that it works perfectly.

The REST web service method is like this:

@POST
@Path("/saveImage")
public Response saveImage(
    @FormDataParam("imagefile") InputStream uploadedInputStream,
    @FormDataParam("imagefile") FormDataContentDisposition fileDetail) {

    // save image on server's file system and return OK
}

Scanned images are available to me by the scanner's local web server through a link like this: http://localhost:9980/thumb/random-generated-guid.jpg

In my angularjs code, I want to send the image which is available with the link above to my REST service.

Does anybody know how to do this?

I tried first saving the image as a blob and then send it to the web service. I could save the image using javascript's XMLHttpRequest but sending always fails. Code for saving the image as 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);
    }
};

Code for sending the blob data:

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();
        });
    };

Actually, the problem is when the sendToGateway(imageData); is called, I get the error:

TypeError: 'append' called on an object that does not implement interface FormData.

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

oops, I found the problem. I should have added the following directives to the $.ajax() call.

processData: false,
contentType: false,

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM