Vue上传文件,不必使用什么element 的uplaod, 也不用什么npm上找的个人写的包,就用原生的Vue加axios就行了, 废话不多说,直接上代码:
html:
<input type="file" value="" id="file" @change="uploadConfig">
注意这里的type是file,就表示是上传文件了
js:
uploadConfig(e) { let formData = new FormData(); formData.append('file', e.target.files[0]); let url = this.$store.state.path + "api/tools/handle_upload_file"; let config = { headers:{'Content-Type':'multipart/form-data'} }; this.$axios.post(url,formData, config).then(function (response) { console.log(response.data) }) }
1. vue里面的axios,如果要用这种方式写,注意请求方式是method, 而不是 type:
this.$axios({
url:this.$store.state.path + "api/tools/handle_upload_file",
method: "POST", // 这个地方注意
data: formData,
file:e.target.files[0],
processData:false,
contentType:false,
success:(response) => {
console.log("upload_success_response:", response)
}
})
2. 传输文件类型,必须加上请求头: headers:{'Content-Type':'multipart/form-data'}
3. 注意axios的用法
def handle_upload_file(request):
if request.method == "POST":
file = request.FILES.get("file") # 获取文件要用request.FILES
print file
for chunk in file.chunks(): # 分块读取二进制文件的方法
print chunk
return HttpResponse(json.dumps({"meta": 200, "msg": "ok"}))
关于下载文件,有点标题党了,实现文件下载只需要js的几行代码,和vue还真是没多大关系,让你的下载按钮点击后触发下面的函数就行了
函数内容:
let aTag = document.createElement('a');
let blob = new Blob([content]); // 这个content是下载的文件内容,自己修改
aTag.download = file_name; // 下载的文件名
aTag.href = URL.createObjectURL(blob);
aTag.click();
URL.revokeObjectURL(blob);
转自:https://www.cnblogs.com/zhang-can/p/9116159.html