从输入类型文件javascript下载文件

时间:2018-10-16 07:48:42

标签: javascript jquery file-upload download

我正在创建一个Web应用程序,我希望我的用户下载input type="file"中选择的文件

这是我的html

<input type='file' id='fieldID' onchange="return ValidateFileUpload('fieldID')"/>

现在是我的JS

function ValidateFileUpload(ID) {

    var fuData = $('#' + ID);
    var FileUploadPath = fuData[0].value;

    //To check if user upload any file
    if (FileUploadPath == '') {

    } else {
        var Extension = FileUploadPath.substring(
            FileUploadPath.lastIndexOf('.') + 1).toLowerCase();

        //The file uploaded is an image

        if (Extension == "gif" || Extension == "png" || Extension == "bmp"
            || Extension == "jpeg" || Extension == "jpg" || Extension == "pdf" || Extension == "ppt" || Extension == "pptx" || Extension == "doc" ||Extension == "docx"
            || Extension == "xls" || Extension == "xlsx") {

            var file = $('#' + ID)[0].files[0];
            var filename = $('#' + ID)[0].files[0].name;
            var blob = new Blob([file]);
            var url = URL.createObjectURL(blob);

            $(this).attr({ 'download': FileUploadPath, 'href': url });
            filename = "";
        }

        //The file upload is NOT an image
        else {
            alert("Document is not the correct format: pdf,ppt,pptx,doc,docx,xls,xlsx and txt are the only document types allowed for upload. Please try again.");

        }
    }
}

但是我无法下载所选文件,请您帮我下载在文件上传中选择的文件

1 个答案:

答案 0 :(得分:1)

这应该可以解决问题。

<script>
    function DownloadFile() {
        file = input.files[0];
        fr = new FileReader();
        fr.readAsDataURL(file);

        var blob = new Blob([file], { type: "application/pdf" });

        var objectURL = window.URL.createObjectURL(blob);
        console.log(objectURL);

        var link = document.createElement('a');
        link.href = objectURL;
        link.download = "myFileName.pdf";
        link.click();
    }
</script>

<input type="file" id="file" />
<input type='button' value='Download' onclick='DownloadFile();'>

检查:https://utilitiesforprogrammers.blogspot.com/2019/01/download-file-from-input-type-file.html