Vue+Django 处理上传的文件

Vue

            <el-upload
              ref="upload"
              :auto-upload='false' 
              :multiple='false'
              :before-upload="beforeUpload"
              :limit="1" 
              accept=".txt"
              action=""
              type="file"
              :http-request="chooseFile">
              <el-button class="reportFilebtn">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;选择文件</el-button>
            </el-upload>

method


    beforeUpload(file) {
      const fileSuffix = file.name.substring(file.name.lastIndexOf(".") + 1);
      const whiteList = ["txt"];
      if (whiteList.indexOf(fileSuffix) === -1) {
        this.$message.error('上传文件只能是txt格式');
        return false;
      }
    },

    chooseFile(file) {
      this.$refs.upload.clearFiles()
      this.file = file.file

      // if(JSON.stringify(file) != '{}'){
      var forms = new FormData()
      var configs = {
        headers:{'Content-Type':'multipart/form-data'}
      }
      forms.append('errList',this.uartlogForm.errList)
      forms.append('uartFile',this.file)

      this.logCheckStation = []
      uartLogTool(forms, configs).then(response => {
 	})   
},

Api.js

export const uartLogTool = (params)=>{
    return axios.post(`tool/uartParseErr`,params)
}

Py文件

def uartParseErr(request):

    if request.method == 'POST':
        response = {}
        
        uartFileData = request.FILES.get('uartFile', None)
        dutErrStr = request.POST.get('dutErrList','ERROR,Fail,Not Found').strip(',,')
        smokeyErrStr = request.POST.get('smokeyErrList','Not Found,All errors').strip(',,')

	#使用该方法缓存InMemoryFiles至Media/tmp文件夹,然后只需要把路径复制过去即可解析
        storageTempPath    = default_storage.save('tmp/{}'.format(uartFileData), ContentFile(uartFileData.read()))
        uartFilePath = os.path.join(settings.MEDIA_ROOT,storageTempPath)

        with open(uartFilePath,'r',encoding="utf-8") as file:
            log_data =  file.read()
	# 处理文件的代码省略


        try:
            response['uartData'] = dict_uart_log_data
            response['stationID'] = STATION_ID
            response['overlayVer'] = OVERLAY_VERSION
            response['msg'] = 'success'
            response['error_num'] = 0
        except Exception as e:
            #print(traceback.format_exc(limit=1))
            response['msg'] = str(e)
            response['error_num'] = 1

        #删除之前缓存的文件,避免内存臃肿
        os.remove(uartFilePath)
        return JsonResponse(response)
  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值