gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 23:06:40 27 4
gpt4 key购买 nike

我正在创建一个网络应用程序,我希望我的用户下载他们在 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.");

}
}
}

但是我无法下载所选文件,您能帮我下载文件上传中所选的文件吗

最佳答案

这应该可以解决问题。

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

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

关于javascript - 从输入类型文件javascript下载文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52830420/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com