Send image through Http Post

1

Hello everyone, I'm trying to send a node file (Client) to my Java web service using Jersey the file is received correctly using POSTMAN this is my Java code:

@POST
@Path("eliminar")
@Consumes({ MediaType.MULTIPART_FORM_DATA, ("text/plain") })
@Produces(MediaType.APPLICATION_JSON)
public Response eliminar(
        @FormDataParam("attachment") InputStream fileInputStream,
        @FormDataParam("attachment") FormDataContentDisposition cdh){
        try{
            if(fileInputStream==null){
             System.out.println("Nulo");    
            }else{                  
                 saveFile(fileInputStream, "C://logs/"+ObjectId.get().toString()+".png");
            }
        }catch(Exception e){
             System.out.println("Catch "+e.getMessage());                                       
        }
    return Response.ok().entity("Eliminar").build();
}

private void saveFile(InputStream uploadedInputStream,String serverLocation) {
    try {
        System.out.println(serverLocation);
        OutputStream outpuStream = new FileOutputStream(new File(serverLocation));
        int read = 0;
        byte[] bytes = new byte[1024];
        outpuStream = new FileOutputStream(new File(serverLocation));
        while ((read = uploadedInputStream.read(bytes)) != -1) {
            outpuStream.write(bytes, 0, read);
        }
        outpuStream.flush();
        outpuStream.close();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

In this part I only move the file I receive to another folder, to check that it has been received correctly.

  

Node Code:

conImagen: function() {
  var bitmap = fs.readFileSync("C:/Users/obar/Desktop/prueba.png"); // Intento subir este archivo como muestra
  var valor= new Buffer(bitmap).toString('base64'); // genero el buffer para enviarlo por Post
  var parts = {
    attachment: {
      contentType: 'image/png',
      filename: 'prueba.png',
      value:valor,
    }
  };
  var formData = MultipartFormData(parts);
  HTTP.call(
    'POST',
    'http://localhost:8080/restdemo/jaxrs/customers/eliminar', {
      content: formData.content,
      headers: formData.headers
    },
    function(error, result) {
      if (error) {
        console.log(error, 'Error');
      }
      if (result) {
        var statusCode=result.statusCode;
        var content=result.content;
        console.log("result "+content);
      }
    }
  );
}

My Multipart function is:

MultipartFormData=function(parts) {
var boundary = '----' + (new Date()).getTime();
var bodyString = [];
_.each(parts, function(value, name, blah) {
  console.log("value "+JSON.stringify(value)+" name "+name);
  if (name === 'attachment') {
    bodyString.push(
      '--' + boundary,
      'Content-Disposition: form-data; name="' + name + '";' +
      'filename="' + value.filename + '"',
      'Content-type: ' + value.contentType,
      '',
      value.value);
  } else {
    bodyString.push(
      '--' + boundary,
      'Content-Disposition: form-data; name="' + name + '"',
      '',
      value);
  }
});
bodyString.push('--' + boundary + '--', '');
return {
  content: bodyString.join('\r\n'),
  headers: {
    'Content-Type': 'multipart/form-data;boundary=' + boundary
  }
}
}

The file is received but corrupted.

    
asked by Rastalovely 25.04.2018 в 16:40
source

1 answer

2

I think the problem is that you are uploading the file after transforming its contents to Base64, but on the server side you do not decode it, but you save it as is, so you will have a file that occupies more than the original and that if you open it with a text editor you can see that it only has letters and numbers.

Options:

  • upload it directly in binary format (using a FormData, that's probably what you're doing with Postman)
  • Passes from Base64 to binary on the server.
answered by 25.04.2018 / 18:37
source