Upload a model
Upload a model from a file or a stream into a folder, follow the progress, and find the version it created.
For an application that puts models into BIM.works. An upload targets a folder node: a file whose name is new in the folder creates a model node with version 1, a file with the name of an existing model node adds the next version to it. The reply is the node with its new last_version_uuid, the id the queries and viewers use.
Before you start#
- A login whose credential has the
model:uploadscope and write rights on the folder (Log in with an API token). - The folder's UUID. The root node of the credential is a fine start:
fs.getRootNodeUuid(); a folder by path: List the tree. - A file of a supported type, IFC and the others in File types.
1. Upload from a file#
// Browser: a File from an <input type="file"> or a drop event
const folderUuid = await client.fs.getRootNodeUuid();
const upload = await client.upload.createUploadFromFile(file, folderUuid);
upload.setProgressHandler((label, percentage) => console.log(label, percentage));
upload.setErrorHandler((error) => console.error(error));
const result = await upload.start();
console.log(result.node.last_version_uuid);
// Node.js: a path instead of a File
const nodeUpload = await client.upload.createUploadFromFileName("models/house.ifc", folderUuid);
const nodeResult = await nodeUpload.start();import java.nio.file.Paths;
import java.util.UUID;
import nl.bimbase.bimworks.client.UploadModelResponse;
import nl.bimbase.bimworks.client.upload.UploadBuilder;
UUID folderUuid = client.fs.getRootNodeUuid();
UploadModelResponse response = client.upload.uploadModel(
new UploadBuilder(folderUuid).fromPath(Paths.get("models/house.ifc")));
UUID versionUuid = response.getNewVersionUuid();using System.IO;
Guid folderUuid = client.Fs.GetRootNodeUuid();
AsyncUploadTask task = client.Upload.UploadModel(new UploadBuilder(folderUuid).SetPath(@"models\house.ifc"));
UploadResponse response = task.GetUploadResponse(); // blocks until the checkin is done
Guid versionUuid = response.treeNode.GetLastVersion().Uuid;import java.io.File;
import nl.bimbase.bimworks.sdk.api.AuthApi;
import nl.bimbase.bimworks.sdk.api.ModelApi;
import nl.bimbase.bimworks.sdk.client.ApiClient;
import nl.bimbase.bimworks.sdk.model.Auth;
import nl.bimbase.bimworks.sdk.model.LoginWithApiTokenRequest;
public class Example {
public static void main(String[] args) throws Exception {
// 1. Connect to BIM.works and log in with your API token
ApiClient client = new ApiClient();
client.updateBaseUri("https://bim.works/openapi");
Auth auth = new AuthApi(client)
.loginWithApiToken(new LoginWithApiTokenRequest().token("<your API token>"))
.getAuth();
client.setRequestInterceptor(builder -> builder.setHeader("Authorization", "Bearer " + auth.getBase64()));
// 2. The request
File _file = new File("model.ifc");
String filename = "model.ifc";
// 3. The call
var result = new ModelApi(client).uploadModel(_file, null, filename, null, null, null, null, null, null, null, null, null, null);
// 4. The result
System.out.println(client.getObjectMapper().writerWithDefaultPrettyPrinter().writeValueAsString(result));
}
}using System.Text.Json;
using BIMworks.Sdk.Api;
using BIMworks.Sdk.Client;
using BIMworks.Sdk.Extensions;
using BIMworks.Sdk.Model;
using Microsoft.Extensions.DependencyInjection;
// 1. Connect to BIM.works and log in with your API token
IServiceProvider Connect(string bearer)
{
var services = new ServiceCollection();
services.AddApi(options =>
{
options.AddTokens(new BearerToken(bearer));
options.AddApiHttpClients(http =>
{
http.BaseAddress = new Uri("https://bim.works" + "/openapi");
http.Timeout = Timeout.InfiniteTimeSpan;
});
});
return services.BuildServiceProvider();
}
var login = await Connect("").GetRequiredService<IAuthApi>().LoginWithApiTokenAsync(new LoginWithApiTokenRequest("<your API token>"));
var auth = login.Ok()?.Auth ?? throw new HttpRequestException(login.RawContent, null, login.StatusCode);
var client = Connect(auth.Base64);
var json = client.GetRequiredService<JsonSerializerOptionsProvider>().Options;
// 2. The request
var file = new FileParameter(File.OpenRead("model.ifc"), "model.ifc");
var filename = "model.ifc";
// 3. The call
var response = await client.GetRequiredService<IModelApi>().UploadModelAsync(file: file, filename: filename);
// 4. The result
var result = response.Ok() ?? throw new HttpRequestException(response.RawContent, null, response.StatusCode);
Console.WriteLine(JsonSerializer.Serialize(result, json));import { openAsBlob } from "node:fs";
import { AuthApi, Configuration, ModelApi, ModelVersionToJSON } from "@bimworks/sdk";
// 1. Connect to BIM.works and log in with your API token
const basePath = "https://bim.works/openapi";
const auth = await new AuthApi(new Configuration({ basePath }))
.loginWithApiToken({ loginWithApiTokenRequest: { token: "<your API token>" } });
const client = new Configuration({ basePath, accessToken: typeof auth === "string" ? auth : auth.base64 });
// 2. The request
const request = { file: new File([await openAsBlob("model.ifc")], "model.ifc"), filename: "model.ifc" };
// 3. The call
const result = await new ModelApi(client).uploadModel(request);
// 4. The result
console.log(JSON.stringify(ModelVersionToJSON(result), null, 2));<?php
require __DIR__ . '/vendor/autoload.php';
use BIMworks\Api\AuthApi;
use BIMworks\Api\ModelApi;
use BIMworks\Configuration;
use BIMworks\Model\LoginWithApiTokenRequest;
// 1. Connect to BIM.works and log in with your API token
$client = (new Configuration())->setHost('https://bim.works/openapi');
$auth = (new AuthApi(config: $client))->loginWithApiToken(new LoginWithApiTokenRequest(['token' => "<your API token>"]));
$client->setAccessToken($auth->getBase64());
// 2. The request
$request = ['file' => new SplFileObject('model.ifc'), 'filename' => 'model.ifc'];
// 3. The call
$result = (new ModelApi(config: $client))->uploadModel(...$request);
// 4. The result
echo json_encode($result, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES), PHP_EOL;import json
import bimworks
# 1. Connect to BIM.works and log in with your API token
client = bimworks.ApiClient(bimworks.Configuration(host="https://bim.works/openapi"))
auth = bimworks.AuthApi(client).login_with_api_token(
bimworks.LoginWithApiTokenRequest(token="<your API token>"))
client.configuration.access_token = auth.actual_instance.var_base64
# 2. The request
file = "model.ifc"
filename = "model.ifc"
# 3. The call
result = bimworks.ModelApi(client).upload_model(file=file, filename=filename)
# 4. The result
print(json.dumps(client.sanitize_for_serialization(result), indent=2))The methods: createUploadFromFile/createUploadFromFileName on Upload, UploadApi.uploadModel with an UploadBuilder on UploadApi, Upload.UploadModel with an UploadBuilder on Upload, ModelApi::uploadModel in PHP SDK. Over HTTP the operation is UploadModel, a multipart/form-data request whose reply is the new version:
Bearer <auth token>Authorization: Bearer <auth token>
Accept: application/jsoncurl -X POST "$BIMWORKS_URL/openapi/model/UploadModel" \
-H "Authorization: Bearer $BIMWORKS_TOKEN" \
-F "file=@<file>" \
-F "node_uuid=<node_uuid>" \
-F "filename=<filename>"Without node_uuid the upload goes to the root node of the credential. input_file_type overrides the type derived from the file name (for a misnamed file); format_settings carries point-cloud options. tags (comma-separated, DEMO), validation_settings (a JSON object) and force_reprocessing are the SDK builders' options.
Over HTTP, two fields replace what the SDKs do for you:
hashinstead of the file. Ask LookupModelHashes first: with the size and the xxh64 of the first 32 KiB, then for a known file with the xxh64 of the whole file (seed 18497208744731555, as an unsigned decimal string). When the server knows the file, send itshashand thefilenamewithout afilepart: no bytes travel. A hash the server cannot use answersDefaultErrorCode.NO_STREAM(404) before anything is created; send the file then.wait_msinstead of waiting. The call answers the version when the checkin ends within that many milliseconds, and otherwise202with the checkin's status andjob_uuid. Follow it with GetCheckin, which waits up towait_msitself (at most 5 minutes) and holds the version once the status isDONE, or the error once it isFAILED. A ZIP of models has no job and is always waited for.
2. Or upload from a stream#
When the model is not on disk (it comes from a request, a database, another service), pass the stream and its size. The SDK sends the bytes as they arrive; the size is needed for the deduplication check below.
// Browser or Node.js: an ArrayBuffer you already have
const upload = await client.upload.createUploadFromArrayBuffer(arrayBuffer, "house.ifc", folderUuid);
const result = await upload.start();try (InputStream in = source.openStream()) {
UploadModelResponse response = client.upload.uploadModel(
new UploadBuilder(folderUuid).fromInputStream(in, size).filename("house.ifc"));
}UploadBuilder builder = new UploadBuilder(folderUuid);
builder.stream = File.OpenRead(path);
builder.filename = "house.ifc";
builder.filesize = new FileInfo(path).Length;
UploadResponse response = client.Upload.UploadModel(builder).GetUploadResponse();3. Understand what happens#
- Deduplication. Before sending, the SDK hashes the first 32 KB (xxh64) and asks whether the server already has a file of that size and prefix; if so it hashes the whole file and, on a full match, the server reuses the stored file and only the node and version are created. This is why uploading the same file twice is fast and why the size must be right. The Java builder's
forceReprocessing(true)skips the check and reprocesses. - Same name, new version. A file whose name exists in the folder as a model node becomes that node's next version; uploading straight onto a model node does the same.
- Processing. The call returns when the model is checked in: parsed, indexed, geometry generated. Large models take minutes; the Java builder's timeout defaults to four hours, the JavaScript upload's to eight. Progress arrives through the handler (JavaScript), a
ProgressListeneron the builder (Java) orAddProgressListeneron the task (.NET). - Failures. A file the parser rejects ends with the version in an error state and an error node on the node; the reasons are the error codes listed under StepParserErrorCode and BimWorksErrorCode in Error codes. A missing scope fails with
NON_AUTHORIZED_SCOPE, a missing write right withAuthorizationError.NO_WRITE_RIGHTS.
Check#
List the folder (List the tree): the model node is there, its last_version_uuid equals the one from the reply, and its versions array has grown by one. Run a query on the new version (Run a BQL query): GET type, COUNT(qid) GROUP BY type returns the object types of the file.