Practical 6: Image and Video Upload/Download using MTOM
Aim
Build a SOAP (originally Simple Object Access Protocol) service that uploads and downloads image or video files using MTOM (Message Transmission Optimization Mechanism). Check each file type and size. Download a saved file and compare it with the original.
Theory
A SOAP message uses XML (Extensible Markup Language) text. To put file data inside this text, a program can convert it to base64. This makes the data about one-third larger.
MTOM sends the file as a separate binary attachment. Binary data is the file data itself. The XML message contains a reference to the attachment.
MTOM (Message Transmission Optimization Mechanism), together with XOP (XML-binary Optimized Packaging), solves this: the file travels as a separate binary part of the HTTP (Hypertext Transfer Protocol) message (a multipart/related message), and the XML only contains a small pointer to it: <xop:Include href="cid:…"/>.
Without MTOM: you describe the gift in words inside your letter – the letter becomes huge and slow to read. With MTOM: you send a short letter saying "the gift is in the attached box #1", and send the gift box separately in the same courier. The letter stays small, the gift arrives as it is.
flowchart TB
subgraph Without MTOM
A1["SOAP envelope<br/><data>iVBORw0KGgoAAAANSUhEUg… (base64, +33%)</data>"]
end
subgraph With MTOM / XOP
B1["Part 1 – SOAP envelope (application/xop+xml)<br/><data><xop:Include href='cid:data-attachment'/></data>"]
B2["Part 2 – raw binary (application/octet-stream)<br/>Content-ID: <data-attachment>"]
B1 --- B2
end
| Aspect | base64 inside the XML | MTOM/XOP |
|---|---|---|
| Size sent over the network | +33 % | Original size |
| Content-Type | text/xml |
multipart/related; type="application/xop+xml" |
| Work to read it | A huge XML text | A small XML + a binary stream |
| Good for | Very small data | Images, video, documents |
How to switch it on in JAX-WS (Java API for XML Web Services):
| Side | How |
|---|---|
| Server | Put @MTOM on the service class (this adds an OptimizedMimeSerialization policy to the WSDL (Web Services Description Language)) |
| Client | Pass new MTOMFeature() when getting the port (in the lab: tick Enable MTOM when generating the client) |
MTOM does not change the service's interface – the operation still takes and returns byte[] (xs:base64Binary in the WSDL). Only the way it travels over the network changes, from base64 text to a binary MIME (Multipurpose Internet Mail Extensions) attachment.
Requirements
Use a Jakarta-compatible Metro runtime with Tomcat 10.1. Java 11+ does not include JAX-WS or wsimport; install these tools separately. Keep the runtime, generated client and jakarta.* imports compatible.
JDK (Java Development Kit) 21, Eclipse, Tomcat 10.1 with JAX-WS (Metro), and a sample image resources/photo.png.
The code shows service logic. Add the Jakarta JAX-WS imports and Java collection imports in your project. It keeps files in memory. Checking a filename extension alone does not prove that a file is safe or has the claimed type.
Program – MediaService.java
@MTOM
@WebService(serviceName = "MediaService")
public class MediaService {
private static final Map<String, byte[]> storage = new HashMap<>();
private static final long MAX_BYTES = 5 * 1024 * 1024;
@WebMethod
public String uploadFile(@WebParam(name = "fileName") String fileName,
@WebParam(name = "data") byte[] data) {
String lower = fileName.toLowerCase();
if (!(lower.endsWith(".png") || lower.endsWith(".jpg") || lower.endsWith(".jpeg") || lower.endsWith(".mp4"))) {
throw new IllegalArgumentException("Only .png, .jpg, .jpeg and .mp4 files are allowed");
}
if (data == null || data.length == 0 || data.length > MAX_BYTES) {
throw new IllegalArgumentException("File must be between 1 byte and 5 MB");
}
storage.put(fileName, data);
return "Uploaded " + fileName + " (" + data.length + " bytes)";
}
@WebMethod
public byte[] downloadFile(@WebParam(name = "fileName") String fileName) {
byte[] data = storage.get(fileName);
if (data == null) throw new IllegalArgumentException("File not found: " + fileName);
return data;
}
}
What the code does:
@MTOM– turns on optimised binary transfer.storage– keeps the uploaded files in memory (file name → bytes);MAX_BYTES= 5 MB limit.uploadFile:- Checks the type – only
.png,.jpg,.jpegand.mp4are allowed. - Checks the size – not empty and not more than 5 MB.
- Saves the file and returns a message with its size.
- Checks the type – only
downloadFile– returns the saved bytes, or an error if the file does not exist.
Program – MediaClient.java
MediaService port = new MediaService_Service().getMediaServicePort(new MTOMFeature());
byte[] original = Files.readAllBytes(Paths.get("resources/photo.png"));
System.out.println(port.uploadFile("photo.png", original));
byte[] copy = port.downloadFile("photo.png");
Files.write(Paths.get("downloads/photo-copy.png"), copy);
System.out.println(Arrays.equals(original, copy) ? "Integrity check: OK" : "Integrity check: FAILED");
try {
port.uploadFile("virus.exe", original);
} catch (Exception e) {
System.out.println("Rejected: " + e.getMessage());
}
What the client does:
- Gets the port with MTOM switched on.
- Reads
photo.pngfrom disk and uploads it. - Downloads it again and saves it as
downloads/photo-copy.png. - Compares the original and the copy byte by byte (integrity check).
- Tries to upload a
.exefile to show it is rejected.
Procedure
- Write
MediaServicewith@MTOM, deploy it to Tomcat, and open its WSDL – find the MTOM policy and thexs:base64Binaryparameters. - Generate the client with MTOM enabled, and write
MediaClient. - Run the client: the image is uploaded, downloaded and compared byte by byte.
- Look at the HTTP traffic (TCP (Transmission Control Protocol)/IP (Internet Protocol) monitor): the request is
multipart/related, with anxop:Includein the XML and a separate binary part. - Open
downloads/photo-copy.png– the picture displays correctly. - Upload a
.exe– the service rejects it with a SOAP fault.
Virtual lab · Web Services · 40 min
Practical 6: Upload and download images with MTOM
Build a SOAP media service that receives and returns binary files as MTOM/XOP attachments, validate type and size, upload a real PNG from a Java client, download it again, verify integrity and open the copy.
Output / Observations
Example output for the settings in this lesson:
Read photo.png: 43298 bytes
Uploaded photo.png (43298 bytes)
Downloaded 43298 bytes
Integrity check: OK
Rejected: Only .png, .jpg, .jpeg and .mp4 files are allowed
How the upload looks on the network (shortened):
Content-Type: multipart/related; type="application/xop+xml"; boundary="uuid:…"
--uuid:…
Content-Type: application/xop+xml;charset=utf-8;type="text/xml"
<S:Envelope>…<data><xop:Include href="cid:data-attachment@vlp"/></data>…</S:Envelope>
--uuid:…
Content-ID: <data-attachment@vlp>
Content-Type: application/octet-stream
<43298 raw bytes>
Notice: part 1 is the small XML with only a pointer (cid:data-attachment@vlp); part 2 carries the 43,298 raw bytes – no base64.
Conclusion
Check that an allowed file uploads and downloads correctly. The downloaded bytes should match the original. Check that the service rejects the file types and sizes listed in the program. Read the HTTP trace to find the attachment.
Viva questions
- What problem does MTOM solve? Base64 makes binary data 33 % bigger and slow to parse in SOAP messages.
- What is XOP? XML-binary Optimized Packaging – binary parts are sent separately and pointed to from the XML with
xop:Include. - Which Content-Type does an MTOM message use?
multipart/relatedwithtype="application/xop+xml". - How do you enable MTOM in JAX-WS?
@MTOMon the service;MTOMFeatureon the client. - How was integrity checked? By comparing the original and downloaded byte arrays (
Arrays.equals); a checksum such as SHA-256 (Secure Hash Algorithm with a 256-bit output) can also be used. - Does MTOM change the WSDL operation signature? No – parameters stay
xs:base64Binary; only the transfer encoding changes.
Practise this topic
Hands-on virtual lab
Apply what you just read in a realistic, guided simulation. Free with a verified account.
Create a free account to track your progress and unlock virtual labs.