Loading File Contents Into a JMeter Variable

Sorry for the ongoing spam about JMeter stuff but I am writing a LOT of coding at the moment and I thought I’d share some of the knarly stuff I come accross so others might benefit.

So I had the issue that I need to cobble together MIME HTTP/SOAP calls that contain attachments. JMeter has the ability to add files statically to an HTTP Request (Body Data) but if you need more control you need to roll your own. Best way to do this would be to load the file into a variable and just attach like this:

...
--MIME_boundary
Content-Type: application/pdf
Content-Transfer-Encoding: binary
Content-ID: <MyFile.pdf>
Content-Disposition: attachment; name="MyFile.pdf"

${AttachmentFile}
--MIME_boundary--
...

But how do you get it into the variable?

1st load a variable up with the content. To do this I use a setUp Thread Group which executes a Groovy (JSR223) controller with the following code that loads a JMeter Property up with the data:

import org.apache.jmeter.util.JMeterUtils;
String fileContents = new File('./MyFile.pdf').getText('UTF-8');

fileContents = fileContents.replaceAll( '%', '%25' );
log.debug("AttachmentFile: " + fileContents);
JMeterUtils.setProperty("AttachmentFileProperty", fileContents);

 

This loads the file and encodes all the % signs with %25. You might need more replacements depending on your input data but this should work for most file types. I use a JMeter Property because a variable is not accross threads. So the 1st step in your Thread Group would be to create a variable of your Property.

import org.apache.jmeter.util.JMeterUtils;
vars.put("AttachmentFile", JMeterUtils.getProperty("AttachmentFileProperty"));

 

The alternative would be to use a JMeter Function like this:

${__Property(AttachmentFileProperty, AttachmentFile, NOTFOUND)}

Or paste directly into the HTTP Body Data:

${__P(AttachmentFileProperty, NOTFOUND)}

So I hope that helps you in these tricky scenarios. If you can do this directly in your Thread Group you don’t need to do all the Property steps. You just vars.put it to whatever variable you need.

Note: This needs modification or thought if you are using it in a distributed harness. The remotes/slaves need to have that file locally.

by Oliver Erlewein

Advertisement

2 thoughts on “Loading File Contents Into a JMeter Variable

Leave a Reply to glinius Cancel reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s