前端如何使用post方式下载文件
要实现post下载首先前后端约定好要以form表单形式提交和接收。
思路就是通过创建动态表单,设置相应的参数实现提交。
主要方法:
downloadFile : function(options){
Let downloadiframe = document.getElementById("down-file-form")
If(downloadiframe ){
downloadiframe.remove
} else {
document.body.removeChild(downloadiframe )
}
let config = {...options, method: options.type || "post"}
let form = document.createElement("form")
form.setAttribute("id", "down-file-form")
form.setAttribute("target", "_blank")
form.setAttribute("method", config.method)
form.setAttribute("action", config.url)
form.setAttribute("style", "display:none")
config.data.language = window.lang
// 设置参数
for(let key in config.data){
let input = document.createElement("input")
input.setAttribute("type", "hidden")
input.setAttribute("name", key)
input.setAttribute("value", config.data[key])
form.appendChild(input)
}
document.body.appendChild(form)
form.submit()
}
通过以下方式调用:
downloadFile ({
url: "www.dsiab.com/api/getList",
type: "post",
data: {
accessToken : "put token if need",
name: 'javascript技术分享',
url: "www.dsiab.com"
}
})
发表评论 (审核通过后显示评论):