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

6 javascript jquery file-upload download

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

这是我的 html

<input type='file' id='fieldID' onchange="return ValidateFileUpload('fieldID')"/>
Run Code Online (Sandbox Code Playgroud)

现在我的 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.");

        }
    }
}
Run Code Online (Sandbox Code Playgroud)

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

Nun*_*ias 4

这应该可以解决问题。

<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);

        if (navigator.appVersion.toString().indexOf('.NET') > 0) {
            window.navigator.msSaveOrOpenBlob(blob, 'myFileName.pdf');
        } else {
            var link = document.createElement('a');
            link.href = objectURL;
            link.download = "myFileName.pdf";
            document.body.appendChild(link);
            link.click();
            link.remove();
        }
    }
</script>

<input type="file" id="input" />
<input type='button' value='Download' onclick='DownloadFile();'>
Run Code Online (Sandbox Code Playgroud)

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