Skip to main content

Retrieving and Updating Files in NetSuite

Learn how to retrieve file details, download content, update properties, and delete files from NetSuite File Cabinet.

Prerequisites

  • NetSuite connector configured with fileCabinet resource enabled
  • File ID from uploaded file or search results

Retrieving File Details

Get complete information about a file:

from abstra.connectors import run_connection_action

file_details = run_connection_action(
"netsuite",
"get_file",
{"fileId": "654321"}
)

print(f"Name: {file_details['data']['name']}")
print(f"Size: {file_details['data']['fileSize']} bytes")
print(f"Type: {file_details['data']['fileType']}")
print(f"URL: {file_details['data']['url']}")
print(f"Created: {file_details['data']['createdDate']}")
print(f"Modified: {file_details['data']['lastModifiedDate']}")

Downloading File Content

Download and save file locally:

import base64

# Get file
file_details = run_connection_action(
"netsuite",
"get_file",
{"fileId": "654321"}
)

# Decode content
content_base64 = file_details['data']['content']
content_bytes = base64.b64decode(content_base64)

# Save to disk
filename = file_details['data']['name']
with open(f"downloaded_{filename}", "wb") as f:
f.write(content_bytes)

print(f"✓ Downloaded: {filename}")

Bulk Download

Download multiple files:

import base64
import os

def download_files(file_ids, output_dir="downloads"):
"""Download multiple files from NetSuite"""

# Create output directory
os.makedirs(output_dir, exist_ok=True)

downloaded = []

for file_id in file_ids:
try:
# Get file
result = run_connection_action(
"netsuite",
"get_file",
{"fileId": str(file_id)}
)

# Decode and save
content = base64.b64decode(result['data']['content'])
filename = result['data']['name']
filepath = os.path.join(output_dir, filename)

with open(filepath, "wb") as f:
f.write(content)

downloaded.append(filename)
print(f"✓ Downloaded: {filename}")

except Exception as e:
print(f"❌ Failed to download {file_id}: {str(e)}")

return downloaded

# Usage
file_ids = ["654321", "654322", "654323"]
downloaded_files = download_files(file_ids)
print(f"\n✓ Downloaded {len(downloaded_files)} files")

Updating File Properties

Update Name and Description

from abstra.connectors import run_connection_action

result = run_connection_action(
"netsuite",
"update_file",
{
"fileId": "654321",
"name": "updated_document.pdf",
"description": "Updated financial report for Q4 2025"
}
)

if result['data']['success']:
print("✓ File properties updated")

Replace File Content

import base64

# Read new content
with open("new_version.pdf", "rb") as f:
new_content = base64.b64encode(f.read()).decode('utf-8')

# Update file
result = run_connection_action(
"netsuite",
"update_file",
{
"fileId": "654321",
"content": new_content
}
)

if result['data']['success']:
print("✓ File content replaced")

Move File to Different Folder

# Move to SuiteScripts folder (ID: -10)
result = run_connection_action(
"netsuite",
"update_file",
{
"fileId": "654321",
"folder": {"internalId": "-10"}
}
)

# Move to SuiteFiles folder (ID: -15)
result = run_connection_action(
"netsuite",
"update_file",
{
"fileId": "654321",
"folder": {"internalId": "-15"}
}
)

Deleting Files

Delete Single File

from abstra.connectors import run_connection_action

result = run_connection_action(
"netsuite",
"delete_file",
{"fileId": "654321"}
)

if result['data']['success']:
print("✓ File deleted")

Bulk Delete

Delete multiple files safely:

def delete_files(file_ids):
"""Safely delete multiple files"""
results = {
"deleted": [],
"failed": []
}

for file_id in file_ids:
try:
result = run_connection_action(
"netsuite",
"delete_file",
{"fileId": str(file_id)}
)

if result['data']['success']:
results['deleted'].append(file_id)
print(f"✓ Deleted: {file_id}")
else:
results['failed'].append(file_id)
print(f"❌ Failed: {file_id}")

except Exception as e:
results['failed'].append(file_id)
print(f"❌ Error deleting {file_id}: {str(e)}")

return results

# Usage
file_ids = ["654321", "654322"]
results = delete_files(file_ids)
print(f"\n✓ Deleted {len(results['deleted'])} files")
print(f"❌ Failed {len(results['failed'])} files")

Practical Examples

File Cleanup Script

Delete old temporary files:

from datetime import datetime, timedelta

# Find old temp files
old_date = (datetime.now() - timedelta(days=30)).strftime('%Y-%m-%d')

result = run_connection_action(
"netsuite",
"query",
{
"query": f"""
SELECT id, name, createddate
FROM File
WHERE name LIKE '%temp%'
AND createddate < TO_DATE('{old_date}', 'YYYY-MM-DD')
"""
}
)

# Delete each file
for file in result['data']['items']:
delete_result = run_connection_action(
"netsuite",
"delete_file",
{"fileId": str(file['id'])}
)

if delete_result['data']['success']:
print(f"✓ Deleted: {file['name']}")

print(f"\n✓ Cleaned up {len(result['data']['items'])} old files")

File Versioning

Create new version of file:

import base64
from datetime import datetime

def create_file_version(file_id, new_content_path):
"""Create a new version by updating existing file"""

# Get current file info
current = run_connection_action(
"netsuite",
"get_file",
{"fileId": file_id}
)

# Read new content
with open(new_content_path, "rb") as f:
new_content = base64.b64encode(f.read()).decode('utf-8')

# Update with version suffix
timestamp = datetime.now().strftime('%Y%m%d_%H%M%S')
original_name = current['data']['name']
name_parts = original_name.rsplit('.', 1)
new_name = f"{name_parts[0]}_v{timestamp}.{name_parts[1]}"

result = run_connection_action(
"netsuite",
"update_file",
{
"fileId": file_id,
"name": new_name,
"content": new_content,
"description": f"Updated version from {datetime.now().strftime('%Y-%m-%d %H:%M')}"
}
)

if result['data']['success']:
print(f"✓ Created version: {new_name}")
return new_name

return None

# Usage
create_file_version("654321", "new_report.pdf")

Download Files by Date Range

import base64
import os
from datetime import datetime

def download_files_by_date(start_date, end_date, output_dir="downloads"):
"""Download all files created in date range"""

# Search for files
result = run_connection_action(
"netsuite",
"query",
{
"query": f"""
SELECT id, name, createddate
FROM File
WHERE createddate BETWEEN TO_DATE('{start_date}', 'YYYY-MM-DD')
AND TO_DATE('{end_date}', 'YYYY-MM-DD')
ORDER BY createddate DESC
"""
}
)

# Create output directory
os.makedirs(output_dir, exist_ok=True)

# Download each file
for file_info in result['data']['items']:
file_details = run_connection_action(
"netsuite",
"get_file",
{"fileId": str(file_info['id'])}
)

content = base64.b64decode(file_details['data']['content'])
filepath = os.path.join(output_dir, file_info['name'])

with open(filepath, "wb") as f:
f.write(content)

print(f"✓ Downloaded: {file_info['name']}")

print(f"\n✓ Downloaded {len(result['data']['items'])} files")

# Usage
download_files_by_date("2025-01-01", "2025-12-31")

Error Handling

Always include error handling:

def safe_file_operation(operation, file_id, **kwargs):
"""Safely perform file operations with error handling"""
try:
result = run_connection_action(
"netsuite",
operation,
{"fileId": file_id, **kwargs}
)

if result.get('status') == 'error':
return {
"success": False,
"error": result.get('message', 'Unknown error')
}

return {
"success": True,
"data": result['data']
}

except Exception as e:
return {
"success": False,
"error": str(e)
}

# Usage
result = safe_file_operation("get_file", "654321")
if result['success']:
print(f"✓ File retrieved: {result['data']['name']}")
else:
print(f"❌ Operation failed: {result['error']}")

Best Practices

Check File Exists Before Operations

def file_exists(file_id):
"""Check if file exists"""
result = run_connection_action(
"netsuite",
"query",
{"query": f"SELECT id FROM File WHERE id = {file_id}"}
)
return len(result['data']['items']) > 0

# Usage
if file_exists("654321"):
# Proceed with operation
pass
else:
print("File not found")

Backup Before Deletion

import base64

def delete_with_backup(file_id, backup_dir="backups"):
"""Delete file after creating local backup"""
import os

# Get file
file_details = run_connection_action(
"netsuite",
"get_file",
{"fileId": file_id}
)

# Create backup
os.makedirs(backup_dir, exist_ok=True)
content = base64.b64decode(file_details['data']['content'])
backup_path = os.path.join(backup_dir, file_details['data']['name'])

with open(backup_path, "wb") as f:
f.write(content)

# Delete from NetSuite
delete_result = run_connection_action(
"netsuite",
"delete_file",
{"fileId": file_id}
)

if delete_result['data']['success']:
print(f"✓ Deleted {file_id}, backup saved to {backup_path}")
return True

return False

Troubleshooting

"File not found" errors

Verify file ID:

# Check if file exists
result = run_connection_action(
"netsuite",
"query",
{"query": f"SELECT id, name FROM File WHERE id = {file_id}"}
)

if result['data']['items']:
print(f"File found: {result['data']['items'][0]['name']}")
else:
print(f"File {file_id} does not exist")

"Permission denied" errors

Ensure your NetSuite role has:

  • File Cabinet > View permission
  • File Cabinet > Edit permission (for updates)
  • File Cabinet > Delete permission (for deletions)

Base64 decoding errors

Handle corrupted content:

import base64

try:
content = base64.b64decode(file_details['data']['content'])
except Exception as e:
print(f"❌ Failed to decode content: {str(e)}")

Next Steps

Resources