Vue上传文件,没必要使用什么element 的uplaod, 也不用什么npm上找的我的写的包,就用原生的Vue加axios就好了, 废话很少说,直接上代码:
html:html
<input type="file" value="" id="file" @change="uploadConfig">
注意这里的type是file,就表示是上传文件了
js:vue
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:python
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的用法
后端(python):ios
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还真是没多大关系,让你的下载按钮点击后触发下面的函数就好了
函数内容:npm
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);