Skip to content

Core\Http\Part::bytes

Creates the body of a request, or one field of a form upload, from a string or bytes value your program already has.

You give it the data and a file name. The file name is required, because the other server sees it as the name of the uploaded file. The result is a Core\Http\Part. You pass it as body to send it as the whole request, or put it in multipart to send it as one field of a form. contentType sets the media type, for example text/csv. If you leave it out, a form field is sent as application/octet-stream.

A Core\Http\Part has no methods, so you cannot read the data back from it. In a form upload, a file name or a media type with a quote or a line break is not allowed. The request throws a RuntimeError before anything is sent.

Good to know: the examples run without a network, so every request in them is refused before it is sent. They show an upload of a picture, a file name with a quote, and a nightly CSV report.

Parameters

  • $datasecret tainted string|secret tainted bytesThe bytes to send, as a string or a bytes.
  • $filenamestringThe file name sent to the server. It is required, because the data has no name of its own.

Options

  • contentTypestringoptionalThe media type of this part. The default is the same as for file.

Return value

Returns Core\Http\Part. A part. Pass it as body or as one key of multipart.

Examples

The examples below run with this configuration file.

nvs.toml
# The program may connect to public hosts only.
# `internal = []` allows no address on this computer or on a private network.
[capabilities.net]
internal = []

Uploading a profile picture

<?nvs
// Shows how to upload a picture that your program already has in memory, as one field of a form.
// A small SVG picture. A real program gets it from a user or creates it.
string $picture = '<svg xmlns="http://www.w3.org/2000/svg" width="8" height="8"><circle cx="4" cy="4" r="4"/></svg>';
// `Core\Http\Part::bytes` creates the field. "avatar.svg" is the file name the other server sees.
Core\Http\Part $avatar = Core\Http\Part::bytes($picture, 'avatar.svg', { contentType: 'image/svg+xml' });
// The form has two fields: a plain text field and the picture.
// 10.0.0.7 is a private address, so the call throws a `RuntimeError` before it sends anything.
try {
Core\Http\Response $response = Core\Http\Client::post('http://10.0.0.7/profile', {multipart: [
'userName' => 'ada',
'avatar' => $avatar,
]});
echo 'status: ', $response->status(), "\n";
} catch (RuntimeError $refused) {
echo $refused->message, "\n";
}
Output
Core\Http\Client::post cannot connect to 10.0.0.7: it is private (10/8, 172.16/12, 192.168/16), which `net.internal` does not except
help: add `internal = ["10.0.0.7"]` under `[capabilities.net]` in nvs.toml

A file name with a quote

<?nvs
// Shows what happens when the file name of an uploaded field contains a quote.
// A user chose this file name. The quotes are part of the name.
string $userFileName = 'notes "final".txt';
Core\Http\Part $notes = Core\Http\Part::bytes("Meeting at 10:00.\n", $userFileName, { contentType: 'text/plain' });
// A quote would end the file name early in the form data. So the call throws a
// `RuntimeError` before it sends anything.
try {
Core\Http\Response $response = Core\Http\Client::post('https://203.0.113.10/upload', { multipart: ['file' => $notes] });
echo 'status: ', $response->status(), "\n";
} catch (RuntimeError $refused) {
echo $refused->message, "\n";
}
// Remove the quotes from a name that a user chose before you use it. This prints `notes final.txt`.
string $safeName = Core\Str::replace($userFileName, '"', '');
echo $safeName, "\n";
Output
Core\Http\Client::post: `notes "final".txt` is not a filename this request can carry — a quote or a control byte in it would end the part's own header early, which is a second part the caller did not write
notes final.txt

A nightly sales report

<?nvs
// Shows a nightly job that creates a CSV report, compresses it and sends it to a partner's server.
array<array<string>> $orders = [
['1042', 'ada', '19.90'],
['1043', 'grace', '5.00'],
['1044', 'linus', '120.00'],
];
// The report is built in memory. It is never written to a file.
string $csv = "order,customer,total\n";
foreach ($orders as array<string> $order) {
$csv = $csv . Core\Str::join($order, ',') . "\n";
}
// `Core\Compress::compress` returns `bytes`. `Core\Http\Part::bytes` accepts a `bytes` value too.
bytes $packed = Core\Compress::compress($csv, Core\Compress::Codec::Gzip);
Core\Http\Part $report = Core\Http\Part::bytes($packed, 'sales.csv.gz', { contentType: 'application/gzip' });
// The part is the whole body of the request. The server's address is private, so the
// call throws a `RuntimeError` before it sends anything.
try {
Core\Http\Response $response = Core\Http\Client::post('https://192.168.1.20/reports', { body: $report, deadline: 30s });
echo 'sent, status: ', $response->status(), "\n";
} catch (RuntimeError $error) {
echo 'not sent: ', $error->message, "\n";
}
echo 'orders in the report: ', Core\Arr::count($orders), "\n";
Output
not sent: Core\Http\Client::post cannot connect to 192.168.1.20: it is private (10/8, 172.16/12, 192.168/16), which `net.internal` does not except
help: add `internal = ["192.168.1.20"]` under `[capabilities.net]` in nvs.toml
orders in the report: 3