Home > Back-end >  Send a file to a API in Java
Send a file to a API in Java

Time:10-29

I'm using the library QRCodeWriter that create a QR and send it to an API.

The issue is that I have variable os where the image is stored, but I can not able to add it to MultipartEntity to send it (commented line).

The error is: incompatible types: ByteArrayOutputStream cannot be converted to ContentBody entity.addPart("file", os)

I tried a lot of code to convert the image without success.

Any help will be apreciated

    String url =  "https://apiURL.com";
    String accessToken = "123456789";

    QRCodeWriter writer = new QRCodeWriter();
    BitMatrix matrix = writer.encode("https://www.google.com/", BarcodeFormat.QR_CODE, 350, 350);
    BufferedImage image = MatrixToImageWriter.toBufferedImage(matrix);

    ByteArrayOutputStream os = new ByteArrayOutputStream();
    ImageIO.setUseCache(false);
    ImageIO.write(image,"png",os);
    
    context.log(os.toString());
    basicIO.write("TestData");

    MultipartEntity entity = new MultipartEntity();
    //entity.addPart("file", os);

    HttpResponse returnResponse = Request.Post(url).addHeader("Authorization", accessToken).body(entity).execute().returnResponse();
    context.log("Response status: "   returnResponse.getStatusLine().getStatusCode());
    context.log(EntityUtils.toString(returnResponse.getEntity()));
    

CodePudding user response:

It works changing:

entity.addPart("file", os);

to:

entity.addPart("file", new ByteArrayBody(os.toByteArray(), "qr.png"));
  • Related