diango-vue项目-前端上传tif文件并在后端保存

直接上代码

前端:

<template>
    <div>
        <el-upload
  class="upload-demo"
  :action="uploadURL"
  :on-preview="handlePreview"
  :on-remove="handleRemove"
  :before-remove="beforeRemove"
  multiple
  :limit="3"
  :on-exceed="handleExceed"
  :on-change="handleChange"
  :file-list="fileList">
  <el-button size="small" type="primary">点击上传</el-button>
  <div slot="tip" class="el-upload__tip">只能上传jpg/png文件,且不超过500kb</div>
</el-upload>
    </div>
</template>
<script>
  export default {
    data() {
      return {
        // 图片要传到服务端的哪里(路由=process.env.VUE_APP_BASE_API+你要传图片的接口)
        uploadURL:process.env.VUE_APP_BASE_API+"/WindAnalysis/tifWA/",

        fileList: [{name: 'food.jpeg', url: 'https://fuss10.elemecdn.com/3/63/4e7f3a15429bfda99bce42a18cdd1jpeg.jpeg?imageMogr2/thumbnail/360x360/format/webp/quality/100'}, {name: 'food2.jpeg', url: 'https://fuss10.elemecdn.com/3/63/4e7f3a15429bfda99bce42a18cdd1jpeg.jpeg?imageMogr2/thumbnail/360x360/format/webp/quality/100'}]
      };
    },
    methods: {

      handleRemove(file, fileList) {
        console.log(file, fileList);
      },
      handlePreview(file) {
        console.log(file);
      },
      handleExceed(files, fileList) {
        this.$message.warning(`当前限制选择 3 个文件,本次选择了 ${files.length} 个文件,共选择了 ${files.length + fileList.length} 个文件`);
      },
      beforeRemove(file, fileList) {
        return this.$confirm(`确定移除 ${ file.name }`);
      }
    }
  }
</script>

后端

import os
import json
import time
from django.conf import settings


# Create your views here.
from django.http import JsonResponse, response, HttpResponse, StreamingHttpResponse


def tifWA(request):
    result = []
    if request.method == 'POST':
        print("函数已触发")
        tif = request.FILES.get('file')  # 至于为什么这里的接收名称位file,我忘了。。。。
        print(tif)
        base_dir = settings.BASE_DIR  # 当前的最高级目录(dvadmin-backend)
        timestrap = str(time.time())
        upload_dir = os.path.join(base_dir, 'media', 'Tifs')  # 在主目录下新建文件夹
        print(upload_dir)

        path = os.path.join(upload_dir, tif.name)  # 把前端传过来的图片保存在新建的upload文件夹中
        print(path)
        with open(path, 'wb+') as f:
            for chunk in tif.chunks():
                f.write(chunk)
    return JsonResponse(result)

这代码由于result没有值,所以会报个小错误,不要紧哈

结果

diango-vue项目-前端上传tif文件并在后端保存_第1张图片

你可能感兴趣的:(前端,vue.js,django)