python Django +Vue实现多文件异步上传

python Django +Vue实现多文件异步上传

刚接触python不久,接到个需求需要多文件上传,在网上找了很多,有讲理论的,有讲实现的,但我花了很长时间,才从这些文章中搞懂这个问题,我们来个直接粗暴的,上代码,部分解释加在代码上

html

<!DOCTYPE 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>
    <!--  引入vue和axios -->
    <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("上传成功!")

代码已经完了,有不足之处还请指正

  • 1
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值