Home > Mobile >  javascript download docx file from ajax response
javascript download docx file from ajax response

Time:01-17

I have a django function with return:

...
return FileResponse(open('demo.docx', 'rb'))

I use ajax to get it on client side. Now I need to download it on client side. I use this code:

...
success:function(response){             
                var blob = new Blob([response]);
                var link = document.createElement('a');
                link.href = window.URL.createObjectURL(blob);
                link.download = "file.docx";
                link.click();
        },
...

Edited:

function func(){    

var csrftoken = $("[name=csrfmiddlewaretoken]").val();

$.ajax({
        type: 'POST',
        url: '/myapp/func/',
        headers:{
            "X-CSRFToken": csrftoken
        },
        data: {name:"",'image1': Data1},
        success:function(response){
            
                var blob = new Blob([response]);
                var link = document.createElement('a');
                link.href = window.URL.createObjectURL(blob);
                link.setAttribute('target', '_blank');
                link.download = "file.docx";
                link.click();
            
        },
        error : function(xhr,errmsg,err) {
            alert("ajax error: func");
        } 
});

}

However it downloads a corrupt something, probably not a docx file. How can I get on client side what I read as a docx?

CodePudding user response:

I came to a solution after serching for quite some time:

I added these lines to AJAX:

        xhrFields: {
            responseType: 'blob'
        },

and then after success:

            var blob = new Blob([response], {type: "application/vnd.openxmlformats-officedocument.wordprocessingml.document"});
            var objectUrl = URL.createObjectURL(blob);

CodePudding user response:

The issue might be the missing download attribute on the a element.

Please try this:

success:function(response){             
                    var blob = response.blob();
                    var link = document.createElement('a');
                    link.href = window.URL.createObjectURL(blob);
                    link.setAttribute('target', '_blank');
                    link.download = "file.docx";
                    link.click();
            },
  • Related