Skip to main content

Notifications

Community site session details

Community site session details

Session Id :
Power Pages - General Discussions
Answered

Upload a file in Dataverse file column with Web API

(0) ShareShare
ReportReport
Posted on by 187

Hello,

I've been using Power Apps (mainly canvas) and Power Automate for a few years, but I'm fairly new to Power Pages and the Dataverse API.

I need to upload a file to Dataverse from my Power Pages site, then download this file into a canvas application.

The Power Pages application design required me to use HTML and JavaScript in my application. The problem is that I could not upload a file in my Dataverse table, in a file type column, despite the existing documentation...

I have created a file type column, his logical name is "crcb8_file_content"

 

Here are two of my attempts that send a 500 error :

Attempt 1 :

 

var reader = new FileReader();
reader.readAsDataURL(file); // from an input file
reader.onload = function (e) {
 var encoded = e.target.result.split(',')[1];
 
 webapi.safeAjax({
 type: "POST",
 url: "/_api/crcb8_productorderstest1s",
 contentType: "application/json",
 data: JSON.stringify({
 "crcb8_name": name,
 "crcb8_current_user" : userEmail,
 "crcb8_file_content": encoded
 }),
 success: function (res, status, xhr) {
 console.log("Entity ID: " + xhr.getResponseHeader("entityid"));
 },
 error: function (xhr, status, error) {
 console.log("error: "+ error)
 } 
 });
}

 

 

Attempt 2 :

 

webapi.safeAjax({
 type: "POST",
 url: "/_api/crcb8_productorderstest1s",
 contentType: "application/json",
 data: JSON.stringify({
 "crcb8_name": name,
 "crcb8_current_user": userEmail
 }),
 success: function (res, status, xhr) {

 var newRecordId = xhr.getResponseHeader("entityid");

 console.log("Entity ID: " + newRecordId + " now attach the file");

 // Now attach the file to the entity unsing safeAjax and PATCH
 var reader = new FileReader();
 reader.readAsDataURL(file); // from input file type
 reader.onload = function (e) {
 var encoded = e.target.result.split(',')[1];

 webapi.safeAjax({
 type: "PATCH",
 url: "/_api/crcb8_productorderstest1s(" + newRecordId + ")/crcb8_file_content",
 contentType: "application/octet-stream",
 processData: false,
 data: encoded,
 success: function (res, status, xhr) {
 console.log("File attached");
 },
 error: function (xhr, status, error) {
 console.log("error: " + error)
 }
 });
 }
 },
 error: function (xhr, status, error) {
 console.log("error: " + error)
 }
});

 

 

Your help would be very useful to me and I thank you in advance!

Categories:
  • swaminawale Profile Picture
    195 on at
    Re: Upload a file in Dataverse file column with Web API

    Hi @CharlesPP  @ragavanrajan 

     

    Thanks for this post. I was looking for it. 

    Is there any way that we can update/replace existing attchment?

     

     

  • CharlesPP Profile Picture
    187 on at
    Re: Upload a file in Dataverse file column with Web API

    The problem disappeared as it happened: no action on our part, false alarm, you can use this code!

  • CharlesPP Profile Picture
    187 on at
    Re: Upload a file in Dataverse file column with Web API

    Hello,

    The code given in my previous message has suddenly been throwing errors (error 500) on my various environments since Saturday, even though no changes have been made. Have you ever encountered a similar problem? Thanks

  • Verified answer
    CharlesPP Profile Picture
    187 on at
    Re: Upload a file in Dataverse file column with Web API

    Thank you @ragavanrajan for the article ! 

     

    I finally used this code: 

    submitForm.addEventListener("click", () => {
     showLoader();
    
     const lines = document.querySelectorAll(".line");
    
     let promises = [];
    
     // Create an order for each product
     remainingFiles.forEach((file, i) => {
     const line = lines[i];
     [get line data]
    
     let promise = new Promise((resolve, reject) => {
     webapi.safeAjax({
     type: "POST",
     url: "/_api/cg_commandes",
     contentType: "application/json",
     data: JSON.stringify({
     "cg_name": clientNameContent,
     "cg_Contact@odata.bind": "/contacts({{user.id}})",
     "cg_Produits@odata.bind": "/cg_produitses(" + productId + ")",
     "cg_typeproduit": productTypeValue,
     "cg_commentaire": commentContent
     }),
     success: function (res, status, xhr) {
    
     const newRecordId = xhr.getResponseHeader("entityid");
    
     // Now attach the file to the entity using safeAjax and PATCH
     const reader = new FileReader();
     reader.onload = function (e) {
     const bodyContents = e.target.result;
     const buffer = new Uint8Array(bodyContents);
    
     // Wrap the safeAjax call in a new promise
     let innerPromise = new Promise((innerResolve, innerReject) => {
     webapi.safeAjax({
     type: "PUT",
     url: "/_api/cg_commandes(" + newRecordId + ")/cg_fichierstl?x-ms-file-name=" + userCompanyCondensed + "-" + fileName,
     contentType: "application/octet-stream",
     processData: false,
     data: buffer,
     success: function (res, status, xhr) {
     innerResolve(); // Resolving the inner promise
     },
     error: function (xhr, status, error) {
     console.log("error: " + error);
     innerReject(error); // Rejecting the inner promise
     }
     });
     });
    
     innerPromise.then(() => {
     hideLoader();
     resolve(); // Resolve the external promise
     }).catch((error) => {
     hideLoader();
     reject(error); // Reject the external promise
     });
     };
     reader.readAsArrayBuffer(file);
     },
     error: function (xhr, status, error) {
     console.log("error: " + error);
     hideLoader();
     reject(error); // Reject the external promise
     }
     });
     });
    
     promises.push(promise); // Add the promise to the table
     });
    
     // Wait until all promises are resolved
     Promise.all(promises).then(() => {
     console.log("Tous les fichiers ont été envoyés avec succès.");
     resetForm();
     }).catch((error) => {
     console.error("Erreur lors de l'envoi des fichiers :", error);
     });
    });


    This works fine, the only problem is that when users submit multiple large files, if they close the page before the submission is complete (which can be quite long with a slow connection), we have the command created without the file. If you have a proposal to solve this problem, I am very interested.

  • ragavanrajan Profile Picture
    7,036 Most Valuable Professional on at
    Re: Upload a file in Dataverse file column with Web API

    Hi @CharlesPP 

     

    Can you try the below article

     

    https://francomusso.com/upload-to-a-file-column-on-record-creation-using-the-portal-web-api 

     

    Hope it helps. 
    ------------

    If you like this post, give it a Thumbs up. Where it solved your request, Mark it as a Solution to enable other users to find it.

Under review

Thank you for your reply! To ensure a great experience for everyone, your content is awaiting approval by our Community Managers. Please check back later.

Helpful resources

Quick Links

Michael Gernaey – Community Spotlight

We are honored to recognize Michael Gernaey as our June 2025 Community…

Congratulations to the May Top 10 Community Leaders!

These are the community rock stars!

Announcing the Engage with the Community forum!

This forum is your space to connect, share, and grow!

Leaderboard > Power Pages

#1
Fubar Profile Picture

Fubar 69 Super User 2025 Season 1

#2
oliver.rodrigues Profile Picture

oliver.rodrigues 49 Most Valuable Professional

#3
Jon Unzueta Profile Picture

Jon Unzueta 43