AnsweredAssumed Answered

Upload KML file programmatically

Question asked by zyishai on Oct 8, 2017
Latest reply on Oct 10, 2017 by zyishai

Hi,

I'm trying to use the arcgis rest api to upload kml file to the portal. I made addItem request and then addPart request to upload the file itself. The documentation does not mention how to send the file, so I read the content of the file as text and send it but I'm getting Internal Server Error response.

 

Here is my code (I also added the js file as attachment):

// get list of files
var files = this.fileSelect.files;

// continue only if the user select one (or more) files
if (files.length > 0) {
   this.uploadButton.innerHTML = "Uploading..";

   var file = files[0];

   fetch('https://www.arcgis.com/sharing/rest/content/users/*****/addItem', {
      method: 'post',
      headers: {
         'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8'
      },
      body: 'token='+encodeURIComponent(token)+'&f=json&title='+encodeURIComponent(file.name)+'&type=KML&filename='+encodeURIComponent(file.name)+'&multipart='+encodeURIComponent(true)
   })
   .then(res => res.json())
   .then(res => {
      return new Promise(resolve => {
         var id = res.id;

         var fileReader = new FileReader();

         // when finish to read the file, make request with the content of the file
         fileReader.onload = (e) => {
            let data = e.target.result;

            fetch('https://www.arcgis.com/sharing/rest/content/users/****/items/'+id+'/addPart', {
               method: 'post',
               headers: {
                  'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8'
               },
               body: 'token='+token+'&f=json&partNum=1&file='+encodeURIComponent(data)
            })
            .then(res => resolve(res));
         }

         // read file content
         fileReader.readAsText(file);
      });
   })
   .then(res => res.json())
   .then(res => {
      console.log(res); // THIS LINE LOGS "500 - INTERNAL SERVER ERROR..."
      if (res.success) {
         return fetch('https://www.arcgis.com/sharing/rest/content/users/*****/items/'+id+'/commit', {
            method: 'post',
         });
      } else {
         return null; // ...THEN GOES HERE
      }
   })
   .then(res => {
      if (res) {
         return res.json();
      } else {
         return undefined; // ...AND THEN RETURN UNDEFINED!
      }
   })
   .then(res => {
      console.log(res);
   });

 

 

Could someone please explain how to upload small file (kml, less than 5mb) to the portal using arcgis rest api (javascript)?

 

Thank you!

 

p.s sorry if I have grammar mistakes (I'm not native english speaker) ..

Attachments

Outcomes