AnsweredAssumed Answered

Exporting Attachments from a Related Table

Question asked by hildecool on Jun 17, 2019

Does anyone have a script that will download attachments from an sde related table? Ideally the script allow the user to download only the attachments related to a subset of features selected from the original feature class.  For example, only download the attachments related to records in the related feature class where "PROJECT" = \'PROJECT NAME\'.  I would also like the script to rename to exported files to the ID of the features class + A.  For example, feature ID 1234 would export attachments 1234A.jpg and 1234B.jpg.  Here's what I have written so far:


import arcpy, os
from collections import defaultdict

inFC = r'Database Connections\LDI_COMPREHENSIVE_WEB_DB.sde\LDI_COMPREHENSIVE_WEB.SDE.WebCollection\LDI_COMPREHENSIVE_WEB.SDE.SurveyPoints' # Feature Class
inTable = r'Database Connections\LDI_COMPREHENSIVE_WEB_DB.sde\LDI_COMPREHENSIVE_WEB.SDE.SurveyPoints__ATTACH' # Attachment table
fileLocation = r'W:\Projects\Path' # Output location

# Get dictionary of ObjectID and associated field value
myFeatures = dict()
with arcpy.da.SearchCursor(inFC, ['GlobalID', 'Transferred_FacilityID'], '"PROJECT" = \'PROJECT NAME\'') as cursor:
for row in cursor:
myFeatures[row[0]] = row[1]

# Create dictionary to count usage of the field value (to increment files)
valueUsage = defaultdict(int)

# Loop through attachments, incrementing field value usage, and using that
# increment value in the filename
with arcpy.da.SearchCursor(inTable, ['DATA', 'ATT_NAME', 'ATTACHMENTID', 'REL_GLOBALID']) as cursor:
for row in cursor:
if row[3] in myFeatures:
attachment = row[0]
fieldValue = myFeatures[row[3]] # Value of specified field in feature class
valueUsage[fieldValue] += 1 # Increment value
filename = "{0}_{1}".format(fieldValue, valueUsage[fieldValue]) # filename = FieldValue_1
output = os.path.join(fileLocation, filename) # Create output filepath
open(output, 'wb').write(attachment.tobytes()) # Output attachment to file
del row
del filename
del attachment



Any help with this would be greatly appreciated!