Add, delete, and download attachments for features from a service.

Use case
Attachments provide a flexible way to manage additional information that is related to your features. Attachments allow you to add files to individual features, including: PDFs, text documents, or any other type of file. For example, if you have a feature representing a building, you could use attachments to add multiple photographs of the building taken from several angles, along with PDF files containing the building’s deed and tax information.
How to use the sample
Tap a feature on the map to open a callout displaying the number of attachments. Tap on the info button to view/edit the attachments. Select an entry from the list to download and view the attachment in the gallery. Tap on the floating action button ’+’ or ’-’ too add or remove an attachment.
How it works
- Create a
ServiceFeatureTablefrom a URL. - Create a
FeatureLayerobject from the service feature table. - Select features from the feature layer with
selectFeatures. - To fetch the feature’s attachments, cast to an
ArcGISFeatureand useArcGISFeature::attachments(). - To add an attachment to the selected ArcGISFeature, create an attachment and use
ArcGISFeature::attachments()::addAttachmentAsync(). - To delete an attachment from the selected ArcGISFeature, use the
ArcGISFeature.deleteAttachmentAsync(). - By default, edits are automatically applied to the service and
applyEditsAsyncdoes not need to be called.
Additional information
Attachments can only be added to and accessed on service feature tables when their hasAttachments property is true.
Relevant API
- ApplyEditsAsync
- AttachmentListModel
- DeleteAttachmentAsync
- FeatureLayer
- FetchAttachmentsAsync
- FetchDataAsync
- ServiceFeatureTable
- UpdateFeatureAsync
Tags
Edit and Manage Data, image, JPEG, picture, PDF, PNG, TXT
Sample Code
// [WriteFile Name=EditFeatureAttachments, Category=EditData]// [Legal]// Copyright 2016 Esri.//// Licensed under the Apache License, Version 2.0 (the "License");// you may not use this file except in compliance with the License.// You may obtain a copy of the License at// http://www.apache.org/licenses/LICENSE-2.0//// Unless required by applicable law or agreed to in writing, software// distributed under the License is distributed on an "AS IS" BASIS,// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.// See the License for the specific language governing permissions and// limitations under the License.// [Legal]
#ifdef PCH_BUILD#include "pch.hpp"#endif // PCH_BUILD
// sample headers#include "EditFeatureAttachments.h"
// ArcGIS Maps SDK headers#include "ArcGISFeature.h"#include "Attachment.h"#include "AttachmentListModel.h"#include "AttributeListModel.h"#include "Basemap.h"#include "CalloutData.h"#include "Envelope.h"#include "Error.h"#include "Feature.h"#include "FeatureEditResult.h"#include "FeatureIterator.h"#include "FeatureLayer.h"#include "FeatureQueryResult.h"#include "IdentifyLayerResult.h"#include "LayerListModel.h"#include "Map.h"#include "MapQuickView.h"#include "MapTypes.h"#include "MapViewTypes.h"#include "Point.h"#include "QueryParameters.h"#include "ServiceFeatureTable.h"#include "SpatialReference.h"#include "Viewpoint.h"
// Qt headers#include <QFile>#include <QFileInfo>#include <QMouseEvent>#include <QUrl>#include <QUuid>
using namespace Esri::ArcGISRuntime;
namespace{ // Convenience RAII struct that deletes all pointers in given container. struct FeatureEditListResultLock { FeatureEditListResultLock(const QList<FeatureEditResult*>& list) : results(list) { } ~FeatureEditListResultLock() { qDeleteAll(results); } const QList<FeatureEditResult*>& results; };}
EditFeatureAttachments::EditFeatureAttachments(QQuickItem* parent) : QQuickItem(parent){}
EditFeatureAttachments::~EditFeatureAttachments() = default;
void EditFeatureAttachments::init(){ qmlRegisterType<MapQuickView>("Esri.Samples", 1, 0, "MapView"); qmlRegisterType<EditFeatureAttachments>("Esri.Samples", 1, 0, "EditFeatureAttachmentsSample"); qmlRegisterUncreatableType<QAbstractListModel>("Esri.Samples", 1, 0, "AbstractListModel", "AbstractListModel is uncreateable"); qmlRegisterUncreatableType<CalloutData>("Esri.Samples", 1, 0, "CalloutData", "CalloutData is an uncreatable type");}
void EditFeatureAttachments::componentComplete(){ QQuickItem::componentComplete();
// find QML MapView component m_mapView = findChild<MapQuickView*>("mapView"); m_mapView->setWrapAroundMode(WrapAroundMode::Disabled);
// create a Map by passing in the Basemap m_map = new Map(BasemapStyle::ArcGISStreets, this); m_map->setInitialViewpoint(Viewpoint(Point(-10800000, 4500000, SpatialReference(102100)), 3e7));
// set map on the map view m_mapView->setMap(m_map);
// create the ServiceFeatureTable m_featureTable = new ServiceFeatureTable(QUrl("https://sampleserver6.arcgisonline.com/arcgis/rest/services/DamageAssessment/FeatureServer/0"), this);
// create the FeatureLayer with the ServiceFeatureTable and add it to the Map m_featureLayer = new FeatureLayer(m_featureTable, this); m_map->operationalLayers()->append(m_featureLayer);
connectSignals();}
void EditFeatureAttachments::connectSignals(){ // connect to the mouse clicked signal on the MapQuickView connect(m_mapView, &MapQuickView::mouseClicked, this, [this](QMouseEvent& mouseEvent) { // first clear the selection m_featureLayer->clearSelection();
// set the properties for qml emit hideWindow();
// call identify on the map view m_mapView->identifyLayerAsync(m_featureLayer, mouseEvent.position(), 5, false, 1).then(this, [this](IdentifyLayerResult* identifyResult) { onIdentifyLayerCompleted_(identifyResult); }); });
// connect to the viewpoint changed signal on the MapQuickView connect(m_mapView, &MapQuickView::viewpointChanged, this, [this]() { m_featureLayer->clearSelection(); emit hideWindow(); });}
QAbstractListModel* EditFeatureAttachments::attachmentModel() const{ return m_selectedFeature ? m_selectedFeature->attachments(false, false) : nullptr;}
void EditFeatureAttachments::addAttachment(const QUrl& fileUrl, const QString& contentType){ if (QFile::exists(fileUrl.toLocalFile())) { const QFileInfo fileInfo(fileUrl.path()); const QString fileName = fileInfo.fileName();
disconnect(m_attachmentConnection); // disconnect previous connection if necessary
if (m_selectedFeature->loadStatus() == LoadStatus::Loaded) { QFile file(fileUrl.toLocalFile()); m_selectedFeature->attachments(false, false)->addAttachmentAsync(file, contentType, fileName).then(this , [this](QFuture<Attachment*>) { applyEdits(); }); } else { m_attachmentConnection = connect(m_selectedFeature, &ArcGISFeature::loadStatusChanged, this, [this, fileUrl, contentType, fileName](Esri::ArcGISRuntime::LoadStatus) { if (m_selectedFeature->loadStatus() == LoadStatus::Loaded) { QFile file(fileUrl.toLocalFile()); disconnect(m_attachmentConnection); m_selectedFeature->attachments(false, false)->addAttachmentAsync(file, contentType, fileName).then(this , [this](QFuture<Attachment*>) { applyEdits(); }); } }); m_selectedFeature->load(); } }}
void EditFeatureAttachments::deleteAttachment(int index){ disconnect(m_attachmentConnection); // disconnect previous connection if necessary
if (m_selectedFeature->loadStatus() == LoadStatus::Loaded) { qDebug() << "Attachments size: " << m_selectedFeature->attachments(false, false)->rowCount(); m_selectedFeature->attachments(false, false)->deleteAttachmentAsync(index).then(this, [this]() { applyEdits(); }); } else { m_attachmentConnection = connect(m_selectedFeature, &ArcGISFeature::loadStatusChanged, this, [this, index](Esri::ArcGISRuntime::LoadStatus) { if (m_selectedFeature->loadStatus() == LoadStatus::Loaded) { disconnect(m_attachmentConnection); m_selectedFeature->attachments(false, false)->deleteAttachmentAsync(index).then(this, [this]() { applyEdits(); }); } }); m_selectedFeature->load(); }}
// process identifyLayerAsync completion on the map viewvoid EditFeatureAttachments::onIdentifyLayerCompleted_(IdentifyLayerResult* identifyResult){ if (!identifyResult) return;
if (!identifyResult->geoElements().empty()) { // select the item in the result m_featureLayer->selectFeature(static_cast<Feature*>(identifyResult->geoElements().at(0)));
// obtain the selected feature with attributes QueryParameters queryParams; m_whereClause = "objectid=" + identifyResult->geoElements().at(0)->attributes()->attributeValue("objectid").toString(); queryParams.setWhereClause(m_whereClause); m_featureTable->queryFeaturesAsync(queryParams).then(this, [this](FeatureQueryResult* featureQueryResult) { onQueryFeaturesCompleted_(featureQueryResult); }); }}
void EditFeatureAttachments::onQueryFeaturesCompleted_(FeatureQueryResult* featureQueryResult){ if (featureQueryResult && featureQueryResult->iterator().hasNext()) { // first delete if not nullptr if (m_selectedFeature) delete m_selectedFeature;
// set selected feature and attachment model members m_selectedFeature = static_cast<ArcGISFeature*>(featureQueryResult->iterator().next(this)); // Don't delete selected feature when parent featureQueryResult is deleted. m_selectedFeature->setParent(this); const QString featureType = m_selectedFeature->attributes()->attributeValue(QStringLiteral("typdamage")).toString(); m_mapView->calloutData()->setLocation(m_selectedFeature->geometry().extent().center()); m_mapView->calloutData()->setTitle(QString("<b>%1</b>").arg(featureType));
emit featureSelected(); emit attachmentModelChanged();
// get the number of attachments // enableAutoFetch and enableAutoApplyEdits for AttachmentListModel are set as false // to avoid automatic behavior. We will call fetchDataAsync explicitly as needed. m_selectedFeature->attachments(false, false)->fetchAttachmentsAsync().then(this, [this](const QList<Attachment*>& attachments) { m_mapView->calloutData()->setDetail(QString("Number of attachments: %1").arg(attachments.size())); m_mapView->calloutData()->setVisible(true); // Resizes the calloutData after details has been set. }); }}
// process completion of applyEditsAsync from the ServiceFeatureTablevoid EditFeatureAttachments::onApplyEditsCompleted_(const QList<FeatureEditResult*>& featureEditResults){ // Lock is a convenience wrapper that deletes the contents of featureEditResults when we leave scope. FeatureEditListResultLock lock(featureEditResults);
if (lock.results.length() > 0) { // obtain the first item in the list FeatureEditResult* featureEditResult = lock.results.first(); // check if there were errors if (!featureEditResult->isCompletedWithErrors()) { qDebug() << "Successfully edited feature attachments";
// update the selected feature with attributes QueryParameters queryParams; queryParams.setWhereClause(m_whereClause); m_featureTable->queryFeaturesAsync(queryParams).then(this, [this](FeatureQueryResult* featureQueryResult) { onQueryFeaturesCompleted_(featureQueryResult); }); } else { qDebug() << "Apply edits error:" << featureEditResult->error().message(); } }}
void EditFeatureAttachments::applyEdits(){ m_featureTable->applyEditsAsync(this).then(this, [this](const QList<FeatureEditResult*>& featureEditResults) { onApplyEditsCompleted_(featureEditResults); });}// [WriteFile Name=EditFeatureAttachments, Category=EditData]// [Legal]// Copyright 2016 Esri.//// Licensed under the Apache License, Version 2.0 (the "License");// you may not use this file except in compliance with the License.// You may obtain a copy of the License at// http://www.apache.org/licenses/LICENSE-2.0//// Unless required by applicable law or agreed to in writing, software// distributed under the License is distributed on an "AS IS" BASIS,// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.// See the License for the specific language governing permissions and// limitations under the License.// [Legal]
#ifndef EDIT_FEATURE_ATTACHMENTS_H#define EDIT_FEATURE_ATTACHMENTS_H
// Qt headers#include <QAbstractListModel>#include <QQuickItem>#include <QtContainerFwd>
namespace Esri::ArcGISRuntime{ class CalloutData; class Map; class MapQuickView; class FeatureLayer; class ServiceFeatureTable; class ArcGISFeature; class IdentifyLayerResult; class FeatureQueryResult; class FeatureEditResult;}
class QString;
class EditFeatureAttachments : public QQuickItem{ Q_OBJECT
Q_PROPERTY(QAbstractListModel* attachmentModel READ attachmentModel NOTIFY attachmentModelChanged)
public: explicit EditFeatureAttachments(QQuickItem* parent = nullptr); ~EditFeatureAttachments() override;
void componentComplete() override; static void init(); Q_INVOKABLE void addAttachment(const QUrl& fileUrl, const QString& contentType); Q_INVOKABLE void deleteAttachment(int index);
signals: void featureSelected(); void hideWindow(); void attachmentModelChanged();
private: void connectSignals(); QAbstractListModel* attachmentModel() const; void applyEdits();
void onIdentifyLayerCompleted_(Esri::ArcGISRuntime::IdentifyLayerResult* identifyResult); void onQueryFeaturesCompleted_(Esri::ArcGISRuntime::FeatureQueryResult* featureQueryResult); void onApplyEditsCompleted_(const QList<Esri::ArcGISRuntime::FeatureEditResult*>& featureEditResults);
Esri::ArcGISRuntime::Map* m_map = nullptr; Esri::ArcGISRuntime::MapQuickView* m_mapView = nullptr; Esri::ArcGISRuntime::FeatureLayer* m_featureLayer = nullptr; Esri::ArcGISRuntime::ServiceFeatureTable* m_featureTable = nullptr; Esri::ArcGISRuntime::ArcGISFeature* m_selectedFeature = nullptr; QString m_whereClause; QMetaObject::Connection m_attachmentConnection;};
#endif // EDIT_FEATURE_ATTACHMENTS_H// [WriteFile Name=EditFeatureAttachments, Category=EditData]// [Legal]// Copyright 2016 Esri.//// Licensed under the Apache License, Version 2.0 (the "License");// you may not use this file except in compliance with the License.// You may obtain a copy of the License at// http://www.apache.org/licenses/LICENSE-2.0//// Unless required by applicable law or agreed to in writing, software// distributed under the License is distributed on an "AS IS" BASIS,// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.// See the License for the specific language governing permissions and// limitations under the License.// [Legal]
import QtQuickimport QtQuick.Controlsimport Qt.labs.platformimport Esri.Samplesimport Esri.ArcGISRuntime.Toolkit
EditFeatureAttachmentsSample { id: editAttachmentsSample
readonly property var featAttributes: ["Destroyed", "Major", "Minor", "Affected", "Inaccessible"]
// add a mapView component MapView { id: mapView anchors.fill: parent objectName: "mapView"
Component.onCompleted: { // Set the focus on MapView to initially enable keyboard navigation forceActiveFocus(); }
Callout { id: callout background: Rectangle { border.color: "lightgrey" border.width: 1 } calloutData: mapView.calloutData leaderPosition: Callout.LeaderPosition.Automatic onAccessoryButtonClicked: { attachmentWindow.visible = true; } } }
onFeatureSelected: { // show the callout callout.showCallout(); }
onHideWindow: { // hide the callout if (callout.visible) callout.dismiss(); attachmentWindow.visible = false; }
// attachment window Rectangle { id: attachmentWindow anchors.centerIn: parent height: 200 width: 250 visible: false radius: 10 color: "lightgrey" border.color: "darkgrey" opacity: 0.90 clip: true
// accept mouse events so they do not propogate down to the map MouseArea { anchors.fill: parent onClicked: mouse => mouse.accepted = true onWheel: wheel => wheel.accepted = true }
Rectangle { id: titleText anchors { left: parent.left right: parent.right top: parent.top } height: 40 color: "transparent"
Text { anchors { verticalCenter: parent.verticalCenter left: parent.left margins: 10 } text: "Attachments" font { bold: true pixelSize: 20 } }
Row { anchors { verticalCenter: parent.verticalCenter right: parent.right margins: 10 } spacing: 15 Text { text: "+" font { bold: true pixelSize: 40 } color: "green"
// open a file dialog whenever the add button is clicked MouseArea { anchors.fill: parent onClicked: { fileDialog.open(); } } } Text { text: "-" font { bold: true pixelSize: 40 } color: "red"
// make sure an item is selected and if so, delete it from the service MouseArea { anchors.fill: parent onClicked: { if (attachmentsList.currentIndex !== -1) { // Call invokable C++ method to add an attachment to the model editAttachmentsSample.deleteAttachment(attachmentsList.currentIndex); } } } } } }
ListView { id: attachmentsList anchors { left: parent.left right: parent.right top: titleText.bottom bottom: parent.bottom margins: 10 } clip: true spacing: 5 // set the model equal to the C++ attachment list model property model: editAttachmentsSample.attachmentModel // create the delegate to specify how the view is arranged delegate: Item { height: 45 width: attachmentsList.width clip: true
// show the attachment name Text { id: label anchors { verticalCenter: parent.verticalCenter left: parent.left right: attachment.left } text: name wrapMode: Text.WrapAnywhere maximumLineCount: 1 elide: Text.ElideRight font.pixelSize: 16 }
// show the attachment's URL if it is an image Image { id: attachment anchors { verticalCenter: parent.verticalCenter right: parent.right } width: 44 height: width fillMode: Image.PreserveAspectFit source: attachmentUrl }
MouseArea { id: itemMouseArea anchors.fill: parent onClicked: { attachmentsList.currentIndex = index; } } }
highlightFollowsCurrentItem: true highlight: Rectangle { height: attachmentsList.currentItem.height color: "lightsteelblue" } } }
// file dialog for selecting a file to add as an attachment FileDialog { id: fileDialog folder: { const locs = StandardPaths.standardLocations(StandardPaths.PicturesLocation) return locs.length > 0 ? locs[locs.length - 1] : ""; } onAccepted: { // Call invokable C++ method to add an attachment to the model editAttachmentsSample.addAttachment(fileDialog.file, "application/octet-stream"); } }}// [Legal]// Copyright 2015 Esri.//// Licensed under the Apache License, Version 2.0 (the "License");// you may not use this file except in compliance with the License.// You may obtain a copy of the License at// http://www.apache.org/licenses/LICENSE-2.0//// Unless required by applicable law or agreed to in writing, software// distributed under the License is distributed on an "AS IS" BASIS,// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.// See the License for the specific language governing permissions and// limitations under the License.// [Legal]
// sample headers#include "EditFeatureAttachments.h"
// ArcGIS Maps SDK headers#include "ArcGISRuntimeEnvironment.h"
// Qt headers#include <QCommandLineParser>#include <QDir>#include <QGuiApplication>#include <QQmlApplicationEngine>#include <QQmlEngine>#include <QQuickView>#include <QSettings>
// Other headers#include "Esri/ArcGISRuntime/Toolkit/register.h"
// Platform specific headers#ifdef Q_OS_WIN#include <Windows.h>#endif
#define STRINGIZE(x) #x#define QUOTE(x) STRINGIZE(x)
int main(int argc, char *argv[]){ Esri::ArcGISRuntime::ArcGISRuntimeEnvironment::setUseLegacyAuthentication(false); QGuiApplication app(argc, argv); app.setApplicationName(QString("Edit Feature Attachments"));
// Use of ArcGIS location services, such as basemap styles, geocoding, and routing services, // requires an access token. For more information see // https://links.esri.com/arcgis-runtime-security-auth.
// The following methods grant an access token:
// 1. User authentication: Grants a temporary access token associated with a user's ArcGIS account. // To generate a token, a user logs in to the app with an ArcGIS account that is part of an // organization in ArcGIS Online or ArcGIS Enterprise.
// 2. API key authentication: Get a long-lived access token that gives your application access to // ArcGIS location services. Go to the tutorial at https://links.esri.com/create-an-api-key. // Copy the API Key access token.
const QString accessToken = QString("");
if (accessToken.isEmpty()) { qWarning() << "Use of ArcGIS location services, such as the basemap styles service, requires" << "you to authenticate with an ArcGIS account or set the API Key property."; } else { Esri::ArcGISRuntime::ArcGISRuntimeEnvironment::setApiKey(accessToken); }
// Initialize the sample EditFeatureAttachments::init();
// Initialize application view QQmlApplicationEngine engine;
// Add the import Path engine.addImportPath(QDir(QCoreApplication::applicationDirPath()).filePath("qml"));
QString arcGISRuntimeImportPath = QUOTE(ARCGIS_RUNTIME_IMPORT_PATH);
#if defined(LINUX_PLATFORM_REPLACEMENT) // on some linux platforms the string 'linux' is replaced with 1 // fix the replacement paths which were created QString replaceString = QUOTE(LINUX_PLATFORM_REPLACEMENT); arcGISRuntimeImportPath = arcGISRuntimeImportPath.replace(replaceString, "linux", Qt::CaseSensitive); #endif
// Add the Runtime and Extras path engine.addImportPath(arcGISRuntimeImportPath);
Esri::ArcGISRuntime::Toolkit::registerComponents(engine);
// Set the source engine.load("qrc:/Samples/EditData/EditFeatureAttachments/main.qml");
return app.exec();}import QtQuick.Controlsimport Esri.Samples
ApplicationWindow { visible: true width: 800 height: 600
EditFeatureAttachments { anchors.fill: parent }}