The syntax multipart: { file: { name: file, mimeType: "image/png", buffer: image } } comes from the Playwright APIRequestContext (request.post) for testing multipart/form-data uploads.
To send multiple files alongside a single file in Playwright, you must use the FormData API or pass multiple distinct keys, because standard JavaScript objects inside Playwright's multipart option cannot hold duplicate property names.
1. Single File Upload
Pass a plain object to the multipart option where the key matches your backend field name.
import { test, expect } from '@playwright/test';
import fs from 'fs';
test('upload single file', async ({ request }) => {
const imageBuffer = fs.readFileSync('path/to/image.png');
const response = await request.post('/upload', {
multipart: {
file: {
name: 'image.png',
mimeType: 'image/png',
buffer: imageBuffer,
},
title: 'Single Image Upload', // Optional text field
},
});
expect(response.ok()).toBeTruthy();
});
2. Multiple Files (Different Field Names)
If your backend expects distinct field names (e.g., avatar and banner, like Multer's upload.fields()), add multiple keys to the multipart object.
const response = await request.post('/upload-fields', {
multipart: {
avatar: {
name: 'avatar.png',
mimeType: 'image/png',
buffer: fs.readFileSync('path/to/avatar.png'),
},
banner: {
name: 'banner.png',
mimeType: 'image/png',
buffer: fs.readFileSync('path/to/banner.png'),
},
},
});
3. Multiple Files (Same Field Name / Array)
If your backend expects an array of files under one field name (e.g., files[] or uploadedImages, like Multer's upload.array('files')), use Playwright's FormData support instead of a plain object.
test('upload multiple files under same field', async ({ request }) => {
const formData = new FormData();
// Convert Node Buffers to Blobs to append multiple items with the same key
const file1 = new Blob([fs.readFileSync('path/to/image1.png')], { type: 'image/png' });
const file2 = new Blob([fs.readFileSync('path/to/image2.png')], { type: 'image/png' });
formData.append('files', file1, 'image1.png');
formData.append('files', file2, 'image2.png');
formData.append('description', 'Batch upload');
const response = await request.post('/upload-multiple', {
multipart: formData,
});
expect(response.ok()).toBeTruthy();
});
Key Notes
- Omit manual Content-Type headers. Do not manually set
'Content-Type': 'multipart/form-data'in yourheadersobject when using Playwright'smultipartoption, as Playwright automatically generates the required multipart boundary string. - Node version requirement. Native
FormDataandBlobare built into Node.js 18+ (which aligns with modern Playwright APIRequestContext setups).

No comments:
Post a Comment