Edit feature attachments

View inC++QMLView on GitHubSample viewer app

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

screenshot

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

  1. Create a ServiceFeatureTable from a URL.
  2. Create a FeatureLayer object from the service feature table.
  3. Select features from the feature layer with selectFeatures.
  4. To fetch the feature's attachments, cast to an ArcGISFeature and useArcGISFeature::attachments().
  5. To add an attachment to the selected ArcGISFeature, create an attachment and use ArcGISFeature::attachments()::addAttachmentAsync().
  6. To delete an attachment from the selected ArcGISFeature, use the ArcGISFeature.deleteAttachmentAsync().
  7. By default, edits are automatically applied to the service and applyEditsAsync does 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

EditFeatureAttachments.cppEditFeatureAttachments.cppEditFeatureAttachments.hEditFeatureAttachments.qml
Use dark colors for code blocksCopy
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
// [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

#include "EditFeatureAttachments.h"

#include "Map.h"
#include "MapQuickView.h"
#include "Basemap.h"
#include "Viewpoint.h"
#include "Point.h"
#include "SpatialReference.h"
#include "ServiceFeatureTable.h"
#include "FeatureLayer.h"
#include "Feature.h"
#include "ArcGISFeature.h"
#include "FeatureEditResult.h"
#include "FeatureQueryResult.h"
#include "AttachmentListModel.h"
#include "MapViewTypes.h"
#include "MapTypes.h"
#include "LayerListModel.h"
#include "IdentifyLayerResult.h"
#include "QueryParameters.h"
#include "AttributeListModel.h"
#include "FeatureIterator.h"
#include "CalloutData.h"
#include "Error.h"
#include "Attachment.h"
#include "Envelope.h"

#include <QUrl>
#include <QUuid>
#include <QMouseEvent>
#include <QFile>
#include <QFileInfo>

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() : 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());
      auto future = m_selectedFeature->attachments()->addAttachmentAsync(file, contentType, fileName);
      Q_UNUSED(future)
    }
    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);
          auto future = m_selectedFeature->attachments()->addAttachmentAsync(file, contentType, fileName);
          Q_UNUSED(future)
        }
      });
      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()->rowCount();
    auto future = m_selectedFeature->attachments()->deleteAttachmentAsync(index);
    Q_UNUSED(future)
  }
  else
  {
    m_attachmentConnection = connect(m_selectedFeature, &ArcGISFeature::loadStatusChanged,
                                     this, [this, index](Esri::ArcGISRuntime::LoadStatus)
    {
      if (m_selectedFeature->loadStatus() == LoadStatus::Loaded)
      {
        disconnect(m_attachmentConnection);
        auto future = m_selectedFeature->attachments()->deleteAttachmentAsync(index);
        Q_UNUSED(future)
      }
    });
    m_selectedFeature->load();
  }
}

// process identifyLayerAsync completion on the map view
void 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
    connect(m_selectedFeature->attachments(), &AttachmentListModel::fetchAttachmentsCompleted,
            this, [this](const QUuid&, 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 ServiceFeatureTable
void 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();
    }
  }
}

Your browser is no longer supported. Please upgrade your browser for the best experience. See our browser deprecation post for more details.