vue iview upload 组件与laravel 7服务端上传跨域在前端代理解决

21 篇文章 0 订阅

最近在做一个项目,在网上看过很多关于upload组件文章,今天我就总结下自己运用upload组件的心得。

最有力的说明就是代码了,上代码

1.运用iview upload组件上传文件(带token,带参数)

 

<div class="upload-item">
  <Upload
   ref="upload"
   :before-upload="handleUpload"
   :max-size="10240"
   :on-exceeded-size="handleSizeError"
   :format="['xlsx','xlx']"
   :on-format-error="handleFormatError"
   :show-upload-list="true"
   :on-progress="progress"
   :on-success="handleUploadSuccess"
   :on-error="handleUploadFail"
   :data="getUserData"
   :action="uploadUrl">
    <Button icon="ios-cloud-upload-outline">选择上传文件</Button>
  </Upload>
  <div v-if="file !== null">上传文件: {{ file.name }} <Button type="text" @click="upload" :loading="loadingStatus">{{ loadingStatus ? 'Uploading' : 'Click to upload' }}</Button></div>
</div>export default {
    data () {
        return {
          uploadUrl:config.apiPath + '/order/import',
          getUserData: { userInfo: localRead('userInfo'), 'token': getAccessToken() }, //当前用户信息&token
        }
    },
    modalCancel ()  {
      this.showTemplate = false;
      this.$refs.upload.clearFiles();
    },
    handleUpload (file)  {
       this.$refs.upload.clearFiles()
    },
    handleUploadSuccess (response, file, fileList)  {
       if(response.status == 200 && response.data.status != 422){
       } else {
          this.$Message.success(file.name + '导入成功')
          this.getData(this.pageNum, this.pageSize, this.formSearch)
     }
   },
   handleUploadFail (error, file, fileList)  {
      this.$Message.error(file.name + '导入失败,请检查文件')
   },
   handleFormatError (file, fileList)  {
      this.$Message.error(file.name + '文件格式错误,必须是xls或者xlsx')
   },
   handleSizeError (file, fileList)  {
       this.$Message.error(file.name + '文件太大,不能超过10M')
   },
 }

laravel 接口代码大致如下:

public function import(Request $request)
    {

        $data = $request->post();

        if(!isset($data['userInfo'])) {
            return $this->exceptionOut('用户信息获取失败');
        }

        $userInfo = $this->getUser($data);
        if(!isset($userInfo['uid']) || !isset($userInfo['uname']) ) {
            return $this->exceptionOut('用户信息获取失败');
        }

        $file = $request->file('file');
        if(is_null($file) || !$file->isValid()){
            return $this->exceptionOut('文件上传失败');
        }
        
        $mimeType = $file->getClientMimeType();
        if (!in_array($mimeType, array('application/vnd.ms-excel', 'application/x-msexecl','application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', 'application/vnd.ms-office','application/zip','application/octet-stream'))){
            return $this->exceptionOut('上传文件类型错误');
        }
        
        if(!in_array($file->getClientOriginalExtension(), ['xlsx','xlx'])){
            return $this->exceptionOut("文件类型必须是:'xlsx','xlx'");
        }
        // 3.判断大小是否符合 3M
        $tmpFilePath = $file->getRealPath();//临时文件 "/tmp/phpMKWbae"
        $sizeLimit = 3;
        if (filesize($tmpFilePath) >= $sizeLimit * 1024 * 1024) {
            return $this->exceptionOut("'文件大小应小于{$sizeLimit}M'");
        }
        
        $excelParse = new ExcelParse($tmpFilePath);        
        $orderExcelParse = new OrderExcelParse();
        $datas = [];
        $error = [];
        $datas = $orderExcelParse->parse($excelParse, 387);

        if($orderExcelParse->getErrMsg()){
            $this->exceptionOut(implode(';', $orderExcelParse->getErrMsg()));
        }
        
        try{
            if(Order::import($datas, $userInfo)){
                return $this->response([], '操作成功');
            }else{
                return $this->exceptionOut("操作失败");
            }
        } catch (\Exception $ex) {
            $this->exceptionOut($ex->getMessage());
        }
    }

当然了,token校验放在Middleware做处理,也做相应的跨域处理即可

以上就是前端的上传代码了,后台通过解密token后,处理数据返回结果给前端,效果如下:

 

 

 

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值