d.d. d.d. - 4 months ago 7
jQuery Question

Getting error while downloading input file

I have written a html code upload any random file from the computer. I want to download the same file what user chooses using jQuery/javascript. I have written the following code to do the same.



<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script>
$(document).ready(function(){
$('input[type="file"]').change(function(e){
var fileName = e.target.files[0].name;
$("#file").attr("href", fileName);
});
});
</script>
</head>
<body>
<input id="file1" type="file" id="photo" name="photo" value="No file chosen"><br><br>
<a id="file" href="" download>download</a>
</body>
</html>





But I am not getting error while downloading the file.How will I do this?

Answer

I have tried following code, It works :

HTML:

<input id="file1" type="file" id="photo" name="photo" value="No file chosen"><br><br>
        <a id="file" href="" download>download</a>

Script:

<script>
                    $(document).ready(function(){
                      $('input[type="file"]').change(function(e){
                           var tmppath = URL.createObjectURL(e.target.files[0]);
                            //alert(tmppath);

                            $("#file").attr("href", tmppath);
                       });
                    });
        </script>

Please find fiddle here : Click here

Hope it helps you..

Happy coding .. :)

Comments