I have abandoned using Box with PHP because the support is abysmal. Since this is an internal only application anyways, I’m using JavaScript.
I can successfully download a file by searching for it using the /search?query=filename.ext&type=file endpoint. In the response, there are several entries, but I can find the specific file I’m looking for by using JavaScript’s find method checking the entry’s name and parent.id.
When I try to upload a file using the /files/content endpoint, I am getting a 404 from the response using this function:
async uploadFile(filename, rawFiles) {
if (!this.#accessToken) {
const errorMessage = 'Access Token is not set. Please authenticate first.'
console.error(errorMessage);
throw new Error(error);
}
const uploadUrl = 'https://api.box.com/2.0/files/content';
const parentFolderId = '-redacted-';
if (rawFiles?.length === 0) {
const errorMessage = 'Please select a file.'
console.error(errorMessage);
throw new Error(error);
}
const file = rawFiles[0];
const formData = new FormData();
formData.append('attributes', JSON.stringify({
name: filename,
parent: { id: parentFolderId }
}));
formData.append('file', file);
try {
const response = await fetch(uploadUrl, {
method: 'POST',
headers: {
'Authorization': `Bearer ${this.#accessToken}`
},
body: formData
});
if (!response.ok) {
throw new Error(`Server returned ${response.status}: ${response.statusText}`);
}
await response.json();
} catch (error) {
console.error('Upload error:', error);
throw new Error(error);
}
}
I don’t think this is a permission issue because with my search entries because I can confirm that value in the parent.id matches the value I’m passing in my parentFolderId variable. However, the only reason a 404 can be returned per the documentation is:
Returns an error if the parent folder does not exist or if the user is not authorized to access the parent folder.
Edit 2 - So I converted my upload to PHP and made the call through PHP and it works. I don’t understand why doing it from the browser causes it to fail.
Does the client id/application you are making the call with have underlying permissions to upload to the folder? This may not be your user, as JWT and CCG auth types get a service account to represent them upon approval.
@smartoneinok - Yes, if you look at my second edit it works fine in PHP using the same client id, client secret, and enterprise id. It just isn’t working through JavaScript.
The follow code worked for me with a ccg app and my local url added to the cors listing in the box config. I used the global http-server package to host it at a local url. I also updated the folder id in the js to be one my app had access to.