6

I'm trying to encode a file to Base64 in Jmeter to test a web service using the following script:

String file = FileUtils.readFileToString(new File("${filepath}"), "UTF-8");
vars.put("file", new String(Base64.encodeBase64(file.getBytes("UTF-8"))));

This works fine for plain/text files and does not work for other file types correctly.

How could I make it work for other file types?

Conspicuous Compiler
  • 6,403
  • 1
  • 40
  • 52
BlueStar
  • 401
  • 3
  • 9
  • 29

6 Answers6

8

Jmeter has many potions to convert a variable to "Base64", below are a few options

  1. Bean shell pre processor
  2. BeanShell PostProcessor
  3. BeanShell Sampler.

Below is the "bean shell" code, which used in "Bean shell pre processor" to convert variable to Base64

import org.apache.commons.codec.binary.Base64;

String emailIs= vars.get("session");

byte[] encryptedUid = Base64.encodeBase64(emailIs.getBytes());
vars.put("genStringValue",new String(encryptedUid));

Example :

Before Base64 :jdwqoeendwqqm12sdw

After Base64 :amR3cW9lZW5kd3FxbTEyc2R3

Converted using Jmeter :

enter image description here

enter image description here

enter image description here Converted Using base64 site:

enter image description here

Sylhare
  • 5,907
  • 8
  • 64
  • 80
Madhu Cheepati
  • 809
  • 5
  • 12
1

As Groovy is now the preferred JSR223 script language in each JMeter Sampler, Pre- & PostProcessor, Listener, Assertion, etc. this task is pretty easy.

def fileAsBase64 = new File("${filepath}").bytes.encodeBase64().toString()
vars.put("file", fileAsBase64)

Or as one liner:

vars.put("file", new File("${filepath}").bytes.encodeBase64().toString())

That's it.

Sven Döring
  • 3,927
  • 2
  • 14
  • 17
1

Use the function ${__base64Encode(nameofthestring)} to encode the string value and ${__base64Decode(nameofthestring)} to decode the string value.

entpnerd
  • 10,049
  • 8
  • 47
  • 68
0

Your issue comes from the fact that you're considering binary files as text when reading them which is wrong.

Use this for reading the file:

Then encode the byte array in Base64

UBIK LOAD PACK
  • 33,980
  • 5
  • 71
  • 116
  • I tried the following and didn't work. byte[] bytes = FileUtils.readFileToByteArray(new File(("${filepath}").getBytes())); vars.put("file",new String(Base64.encodeBase64(bytes))); – BlueStar Apr 11 '16 at 23:22
0

Try this

import org.apache.commons.codec.binary.Base64;
String forEncoding = vars.get("userName") + ":" + vars.get("passWord");
byte[] token = Base64.encodeBase64(forEncoding.getBytes());
vars.put("token", new String(token));
rjsha
  • 1
  • 2
0

Alternative for this is to directly create a groovy function in User Defined Variable as

${__groovy(new File(vars.get("filepath")).bytes.encodeBase64().toString(),)}
Sud
  • 166
  • 12