Home > Back-end >  How to get file from an action method which is downloading
How to get file from an action method which is downloading

Time:07-31

Here is my sample code which I got from a website which converts xls to xlsx. It downloads the file immediately after converting it to xlsx, so I want to use that file further as blob. so is there any way to use that file which I will receive from action method using JavaScript? Thank you!

HTML Code :

<form action="https://v2.convertapi.com/convert/xls/to/xlsx?Secret=...&download=attachment" method="post" enctype="multipart/form-data">
   <input type="file" name="File" /> 
   <input type="hidden" name="FileName" value="anyName" /> 
   <input type="submit" value="Convert file"/>
</form> 

JavaScript code:

function convert(input){
    let obj = {
        File : input,
        FileName : 'Test'
    }
    $.ajax({
        url: 'https://v2.convertapi.com/convert/xls/to/xlsx?Secret=...&StoreFile=true',
        method: 'POST',
        headers:{
            'content-type' : 'multipart/form-data'
        },    
        body: JSON.stringify(obj),
        success : function(res){
            console.log(res);
        },
        error: function(err){
            console.log(err.responseText);
        }
    })
   }

CodePudding user response:

you would use javascript's fetch() to upload the file to the conversion endpoint instead of using a form, then you would get the file download as a response, which you can do with what you like.

this question may help you figure out how to upload a file, but you will have to understand a bit of javascript:

How do I upload a file with the JS fetch API?

CodePudding user response:

I tried to upload same way as you mentioned @dqhendricks but didn't worked for me. when I tried with FormData it worked for me. It would be awesome if we could do it with just JS.

HTML :

  <form method="post" enctype="multipart/form-data" id="fileUploadForm">
            <input type="file" name="File" />
            <input type="hidden" name="FileName" value="newFile" />
            <input type="button" id="btnSubmit" value="Convert file"/>
   </form>

JS:

$(document).ready(function () {
    $("#btnSubmit").click(function (event) {
        var form = $('#fileUploadForm')[0];
        var d = new FormData(form);

        $.ajax({
            type: "POST",
            enctype: 'multipart/form-data',
            url: 'https://v2.convertapi.com/convert/xls/to/xlsx?Secret=[Secret]&StoreFile=true',
            processData: false,
            contentType: false,
            cache: false,
            data: d,
            timeout: 600000,
            success: function (res) {
                console.log(res);
            },
            error: function (err) {
                console.log(err.responseText);
            }
        })
    });
});
  • Related