vue提交带文件的表单,Django负责接收

11 篇文章 1 订阅

具体的思路:

  • 文件先上传到服务器,由后端返回一个链接
  • 前端接收这个链接后存到变量里,等提交表单时一起把数据传给后端
  • 把数据传给后端时,Django通过一个forms接收数据
  • 把这些数据,以及其他由系统生成的数据组合成一个完整的数据表项,存到数据库中

一、Vue

1.1 template

这部分主要是看5个函数

<el-dialog title="提交" :visible.sync="dialogFormVisible" :append-to-body="true" center>
          <el-form :model="form" ref="submitform">

            <el-form-item label="任务名称" :label-width="formLabelWidth">
              <el-input v-model="form.problemname" autocomplete="off" placeholder="不超过10个字"></el-input>
            </el-form-item>

            <el-form-item label="运行时间上限" :label-width="formLabelWidth">
              <el-input v-model="form.timeout" autocomplete="off" placeholder="以s为单位"></el-input>
            </el-form-item>

            <el-upload
              class="upload-demo"
              :action="uploadZip()"
              :on-preview="handlePreview"
              :on-remove="handleRemove"
              :on-success="getFilePath"
              :before-remove="beforeRemove"
              multiple
              :limit="3"
              :on-exceed="handleExceed"
              :file-list="fileList">
              <el-button size="small" type="primary">点击上传</el-button>
              <div slot="tip" class="el-upload__tip">请上传项目文件或者压缩包</div>
            </el-upload>

            <el-upload
              class="upload-demo"
              :action="uploadSetting()"
              :on-preview="handlePreview"
              :on-remove="handleRemove"
              :on-success="getSettingPath"
              :before-remove="beforeRemove"
              multiple
              :limit="3"
              :on-exceed="handleExceed"
              :file-list="fileList">
              <el-button size="small" type="primary">点击上传</el-button>
              <div slot="tip" class="el-upload__tip">请上传项目配置文件</div>
            </el-upload>

          </el-form>
          <div slot="footer" class="dialog-footer">
            <el-button @click="dialogFormVisible = false">取 消</el-button>
            <el-button type="primary" @click="onSubmit" >确 定</el-button>
          </div>
        </el-dialog>

1.2 script

1.2.1 uploadZip()

uploadZip(){
		//上传文件的路径
        return this.$server+'upload_problemZip/'
      },

1.2.2 getFilePath()

//获取文件上传的路劲
getFilePath(response){
        console.log(this.$server+response.path)
        this.form.Zips_path=this.$server+response.path
      },

1.2.3 uploadSetting()

uploadSetting(){
		//上传文件的路径
        return this.$server+'upload_problemSetting/'
      },

1.2.4 getSettingPath()

getSettingPath(response){
        console.log(this.$server+response.path)
        this.form.Settings_path=this.$server+response.path
      },

1.2.5 onSubmit()

前端往后端传数据时,不能直接传json,要传URLSearchParams对象来传递

onSubmit () {
        this.dialogFormVisible = false
        console.log(this.form)
        let param = new URLSearchParams()
        param.append('problemName',this.form.problemname)
        param.append('timeout',this.form.timeout)
        param.append('type',this.form.type)
        param.append('zip_path',this.form.Zips_path)
        param.append('settings_path',this.form.Settings_path)
        this.$http.post(this.$server+'submitForm/',param
        ).then(function(response){
          console.log(response)
        }).catch(function(error){
          console.log(error)
        })
      },

二、Django

2.2 views.py

2.2.1 处理表单数据

两个注意点:

  • 需要用一个forms类来接收前端的数据
  • 需要用forms.cleaned_data['属性名']来获取表单的数据;而要使用这个cleaned_data,就又要调用forms.is_valid()判断传过来的数据是否合法,比如字符串长度是否合理

代码如下:

# 定义一个forms类,用于接收表单数据
class submitForm(forms.Form):
    problemName = forms.CharField(max_length=100)
    timeout = forms.CharField(max_length=100)
    type = forms.CharField(max_length=100)
    zip_path = forms.CharField(max_length=100)
    settings_path = forms.CharField(max_length=100)
# 存储表单数据,views.py
def saveProblem(request):
    if request.method == "POST" and request.POST:
        submit_form = submitForm(request.POST)
        if submit_form.is_valid():
        # 下面这段就是用表单的数据组合成一个完整的数据表项
            name = submit_form.cleaned_data["problemName"]
            type = submit_form.cleaned_data["type"]
            time_submit = timezone.now().strftime("%Y-%m-%d %H:%M:%S")
            timeout = submit_form.cleaned_data["timeout"]
            status = "1"
            zip_path = submit_form.cleaned_data["zip_path"]
            settings_path = submit_form.cleaned_data["settings_path"]
        # 组合结束    
        
        # 往数据库的problem表中添加一个新的记录
            Problem.objects.create(name=name, type=type, time_submit=time_submit, time_limit=timeout, status=status, fileZip_url=zip_path, fileSetting_url=settings_path)
        # 向前端返回一个JsonResponse对象 
            return JsonResponse({
                "problemName": name,
                "timeout": timeout,
                "type": type,
                "zip_path": zip_path,
                "settings_path": settings_path,
                "result": "success",
            })
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值