//native
type Box = {
token: string;
};
type Base64 = string;
/**
* Upload file version
* Update a file's content. For file sizes over 50MB we recommend
using the Chunk Upload APIs.
The `attributes` part of the body must come **before** the
`file` part. Requests that do not follow this format when
uploading the file will receive a HTTP `400` error with a
`metadata_after_file_contents` error code.
*/
export async function main(
auth: Box,
file_id: string,
fields: string | undefined,
if_match: string,
content_md5: string,
body: {
attributes: { name: string; content_modified_at?: string };
file: {
base64: Base64;
type:
| "image/png"
| "image/jpeg"
| "image/gif"
| "application/pdf"
| "appication/json"
| "text/csv"
| "text/plain"
| "audio/mpeg"
| "audio/wav"
| "video/mp4";
name: string;
};
},
) {
const url = new URL(`https://api.box.com/2.0/files/${file_id}/content`);
for (const [k, v] of [["fields", fields]]) {
if (v !== undefined && v !== "" && k !== undefined) {
url.searchParams.append(k, v);
}
}
const formData = new FormData();
for (const [k, v] of Object.entries(body)) {
if (v !== undefined) {
if (["file"].includes(k)) {
const { base64, type, name } = v as {
base64: Base64;
type: string;
name: string;
};
formData.append(
k,
new Blob([Uint8Array.from(atob(base64), (m) => m.codePointAt(0)!)], {
type,
}),
name,
);
} else {
formData.append(k, String(v));
}
}
}
const response = await fetch(url, {
method: "POST",
headers: {
"if-match": if_match,
"content-md5": content_md5,
Authorization: "Bearer " + auth.token,
},
body: formData,
});
if (!response.ok) {
const text = await response.text();
throw new Error(`${response.status} ${text}`);
}
return await response.json();
}
Submitted by hugo697 235 days ago