刚接触python不久,接到个需求需要多文件上传,在网上找了很多,有讲理论的,有讲实现的,但我花了很长时间,才从这些文章中搞懂这个问题,我们来个直接粗暴的,上代码,部分解释加在代码上
html
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>首页title>
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js">script>
<script src="https://unpkg.com/axios/dist/axios.min.js">script>
head>
<body>
<div id="app">
<input type="file" multiple="multiple" @change="fileChange" name="myfile">
<input type="button" @click="upData" value="上传">
div>
<script>
let app = new Vue({
el: '#app',
data: {
fileList: [],
},
methods: {
fileChange: function (e) {
this.fileList = e.target.files
},
upData:function () {
let that=this
let formData=new FormData();//一个模拟表单提交的对象,
let len=that.fileList.length;
for(let i=0;i<len;i++){
formData.append('myfile',this.fileList[i])
}
axios({
method:"post",
url: "upload/",
data:formData,//注意这里不是用prams提交参数
headers: {
//文件上传要设置的我就不细说了
'Content-Type': 'multipart/form-data;charset=utf-8'
},
}).then((res)=>{
console.log(res);
}).catch(error=>{
alert(error);
});
},
},
})
script>
body>
html>
Django 中urls的
urlpatterns = [
path('upload/', views.upload),
]
Django 中 views的
def upload(request):
# 请求方法为PO5T时,进行处理
if request.method == "POST":
# 获取上传的文件,如果没有文件,则默认为None
myFiles = request.FILES.getlist("myfile", None)
if not myFiles:
return HttpResponse("未接收到文件!")
for myFile in myFiles:
# 打开特定的文件进行二进制的写操作(有更新,无新建)
destination = open(os.path.join("D:\\upload\\", myFile.name), 'wb+')
for chunk in myFile.chunks(): # 分块写入文件
destination.write(chunk)
destination.close()
return HttpResponse("上传成功!")
代码已经完了,有不足之处还请指正