1

I'm trying to upload and download the excel file in a single click operation. I'm calling two APIs in a single operation. The download operation is working fine. But during file upload, an empty excel file is being uploaded with the exact file-name. This is the server side code Excel Duplicates Remover in JAVA. The server-end works fine. And this is the client-side code.

<!DOCTYPE html>
<html>
   <body>
      Select a file: <input type="file" id="file"  accept=".csv, .xls, application/vnd.openxmlformats-officedocument.spreadsheetml.sheet, application/vnd.ms-excel" multiple size="50"/><br>
      Keyword:<input type="text" id="columnHeading"/><br>
      <button type="button" onclick="downloadDoc()">Request data</button>
      <script>
         function downloadDoc(){
         var fileTab = document.getElementById("file");
         var columnHeading = document.getElementById("columnHeading");
         if('files' in fileTab) {
         if(fileTab.files.length == 1) {
         var url = 'http://localhost:8080/excel-duplicate-remover/rest/fileService/';
         var uploadUrl = url + "upload";
         var file=fileTab.files[0];
         var formData = new FormData();
         formData.append("columnHeading",columnHeading);
         formData.append("file",file);
         var xhr = new XMLHttpRequest();
         xhr.onreadystatechange = function() {
             if (this.readyState == 4 && this.status == 200) {
         var response = JSON.parse(this.responseText);
         var path = response.path;
         var downloadUrl = url + 'downloadFile?fileName=' + path;
         downloadFile(downloadUrl);
             }
           };
         xhr.open("POST", uploadUrl);
         xhr.send(formData);
         }else{
         console.log("file not present");
         }
         }
         }

         function downloadFile(filename) {
         console.log("filename"+filename);
           var link = document.createElement('a');
             // Add the element to the DOM
             link.setAttribute("type", "hidden"); // make it hidden if needed
             link.href = filename;
             link.download;
             document.body.appendChild(link);
             link.click();
             link.remove();
         }
      </script>
   </body>
</html>

Why is the file being uploaded as an empty excel file?

Harun
  • 1,137
  • 1
  • 9
  • 7
Chitraveer Akhil
  • 147
  • 1
  • 5
  • 18

0 Answers0