Adding file upload functionality

Loading

File upload functionality is an essential feature for many portals, allowing users to upload documents, images, and other files for storage or processing. In Power Pages (formerly known as Power Apps Portals), file upload features can be integrated with Dataverse or other data sources to handle the uploaded files effectively.

Here’s a step-by-step guide to adding file upload functionality to your Power Pages portal:


Step 1: Create a Dataverse Table for File Storage

Before adding a file upload feature to your portal, you need a location to store the files. Power Pages is integrated with Dataverse, so the best way to manage file uploads is to create a Dataverse table with a file column to store uploaded files.

Create a Dataverse Table for File Upload

  1. Navigate to Power Apps → In the Power Apps portal, go to the Dataverse section and select Tables.
  2. Create a New Table: Click New Table, name it (e.g., UploadedFiles), and configure basic settings.
  3. Add Columns:
    • Add a column of type File (or Multiple File if you need multiple files). You can name it File or something more descriptive like Document.
    • If you want to capture additional metadata (e.g., file name, upload date), you can add other columns such as FileName, UploadDate, etc.

Example:

  • Table Name: UploadedFiles
  • Columns:
    • File (File type)
    • FileName (Text)
    • UploadDate (Date and Time)

Step 2: Add File Upload Control in Power Pages

Now that the table is created, you can integrate the file upload functionality within the portal.

Create a Form for File Upload

  1. Navigate to Power Pages → Open the page where you want to add the file upload feature.
  2. Add a New Web Form:
    • Go to Web PagesAdd New Form.
    • Select the Dataverse Table (UploadedFiles) you just created as the data source.
  3. Add the File Upload Field:
    • Add a form control that binds to the File column of the UploadedFiles table.

Example:

  • Add Input Element for the file upload (HTML form field):
<form id="fileUploadForm" action="submit" method="post" enctype="multipart/form-data">
<input type="file" id="fileInput" name="fileInput" />
<input type="text" id="fileName" name="fileName" placeholder="File Name" />
<button type="submit" id="submitBtn">Upload</button>
</form>

This will create a form where users can select a file to upload.


Step 3: Handle the File Upload with JavaScript

To manage file uploads effectively, you can use JavaScript to handle form submissions, display validation messages, and send the data to Dataverse via Power Pages.

  1. Add JavaScript to Handle the Form Submission:
    • Add an event listener for the form submission that handles file data.

Example JavaScript to Handle File Upload:

document.getElementById("submitBtn").addEventListener("click", function(event) {
event.preventDefault(); // Prevent the default form submission

var fileInput = document.getElementById("fileInput");
var file = fileInput.files[0]; // Get the selected file

if (!file) {
alert("Please select a file to upload.");
return;
}

var formData = new FormData();
formData.append("file", file);
formData.append("fileName", document.getElementById("fileName").value);

// Send the file to the Power Pages portal endpoint
fetch('/api/uploadfile', {
method: 'POST',
body: formData,
})
.then(response => response.json())
.then(data => {
if (data.success) {
alert("File uploaded successfully!");
} else {
alert("Error uploading file.");
}
})
.catch(error => {
console.error('Error:', error);
alert("Error uploading file.");
});
});

Step 4: Create an API or Action to Save the File in Dataverse

Power Pages allows you to leverage custom Web API or Power Automate flows to handle file storage in Dataverse. Here’s how to store the uploaded file in Dataverse:

Option 1: Using Web API

  1. Create a Web API in Power Pages or Power Automate to handle the file upload.
  2. The API should:
    • Accept the file as part of a POST request.
    • Save the file to the Dataverse table (e.g., UploadedFiles).
  3. Example API Endpoint:
    • When the form submits, the JavaScript code will send the file to an API endpoint that saves it in Dataverse.

Example API Call to Store File in Dataverse:

fetch("https://yourdataverse.api.endpoint/UploadedFiles", {
method: 'POST',
headers: {
"Authorization": "Bearer " + accessToken,
"Content-Type": "application/json"
},
body: JSON.stringify({
"FileName": file.name,
"FileContent": fileContentBase64 // Convert the file to base64 or use File API
})
})
.then(response => response.json())
.then(data => {
console.log("File saved successfully", data);
})
.catch(error => {
console.error("Error saving file", error);
});

Option 2: Using Power Automate

Alternatively, you can set up a Power Automate flow triggered by the submission of the form.

  1. Create the Flow:
    • Use Power Automate to trigger the file upload process whenever a file is submitted from the form.
    • The flow should take the file from the form, convert it into a format suitable for Dataverse (Base64 or byte data), and then save it to the UploadedFiles table.
  2. Connect the Form to the Flow:
    • In Power Pages, trigger the flow from the form by using the HTTP connector or custom JavaScript.

Step 5: Displaying Uploaded Files

Once the file is successfully uploaded and saved in Dataverse, you can display the file (or list of files) on the portal. You can use Liquid templates or JavaScript to query Dataverse and show a list of uploaded files.

Example of Displaying Files with Liquid:

{% assign files = entities['uploadedfiles'] %}
<ul>
{% for file in files %}
<li><a href="{{ file.file_url }}">{{ file.file_name }}</a></li>
{% else %}
<li>No files uploaded yet.</li>
{% endfor %}
</ul>

Step 6: Add Validation for File Types and Sizes

To ensure that only valid files are uploaded, you can implement validation on the file input field using JavaScript or within the Dataverse table using business rules.

Example Validation with JavaScript:

var allowedTypes = ['image/jpeg', 'image/png', 'application/pdf'];
var maxSize = 10 * 1024 * 1024; // 10MB

if (!allowedTypes.includes(file.type)) {
alert("Invalid file type. Please upload an image or PDF.");
return;
}

if (file.size > maxSize) {
alert("File is too large. Maximum size is 10MB.");
return;
}

Leave a Reply

Your email address will not be published. Required fields are marked *