温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

Ant Design Upload文件上传功能怎么实现

发布时间:2023-05-06 15:46:18 来源:亿速云 阅读:200 作者:iii 栏目:开发技术

今天小编给大家分享一下Ant Design Upload文件上传功能怎么实现的相关知识点,内容详细,逻辑清晰,相信大部分人都还太了解这方面的知识,所以分享这篇文章给大家参考一下,希望大家阅读完这篇文章后有所收获,下面我们一起来了解一下吧。

一、Ant Design Vue文件上传功能

1.文件上传选项框

 <a-modal
      title="上传文件"
      :footer="null"//不显示底部按钮
      :visible="visible"//是否显示
      :confirmLoading="confirmLoading"//确定按钮 loading
      @cancel="handleCancel"//取消方法
    >
      <a-upload
        :fileList="fileList"//上传的文件列表
        :remove="handleRemove"//文件删除方法
        :beforeUpload="beforeUpload"//上传文件之前的钩子,参数为上传的文件
      >
        <a-button>
          <a-icon type="upload" />选择文件
        </a-button>
      </a-upload>
    </a-modal>
<div class="streetAdd">
      <a-button type="primary" icon="plus" @click="engineeringadd()">新增</a-button>
      <a-button type="primary" icon="file" @click="showModal()">数据导入</a-button>
    </div>

效果:

Ant Design Upload文件上传功能怎么实现

Ant Design Upload文件上传功能怎么实现

2.js实现代码

//定义的变量
<script>
export default {
	data() {
	    return {
	      visible: false,
	      confirmLoading: false,
	      fileList: [],
	      IpConfig: this.IpConfig.projectServiceDomain,
	    }
	  },
	mounted: function () {
	    this.engineeringList()
	    //that.alarmTypes=res.data.res.dictionaryList;
	  },
	   methods: {
		   //点击数据导入按钮所调用的方法
		    showModal() {
		      this.visible = true
		    },
		    //对话框确认方法
		    handleOk(e) {
		      this.visible = false
		      this.confirmLoading = false
		    },
		    //关闭弹框
		    handleCancel(e) {
		      //console.log('Clicked cancel button')
		      this.visible = false
		    },
		    //删除上传文件
		    handleRemove(file) {
		      const index = this.fileList.indexOf(file)
		      const newFileList = this.fileList.slice()
		      newFileList.splice(index, 1)
		      this.fileList = newFileList
		    },
		    //显示上传文件内容
		    beforeUpload(file) {
		      this.spinning = true
		      var that = this
		      that.visible = false
		      //文件类型
		      var fileName = file.name.substring(file.name.lastIndexOf('.') + 1)
		      if (fileName != 'xlsx' && fileName != 'xls') {
		        this.$message.error('文件类型必须是xls或xlsx!')
		        this.spinning = false
		        that.visible = true
		        return false
		      }
		      //读取文件大小
		      var fileSize = file.size
		      //console.log(fileSize)
		      if (fileSize > 1048576) {
		        this.$message.error('文件大于1M!')
		        this.spinning = false
		        that.visible = true
		        return false
		      }
		      let fd = new FormData()//表单格式
		      fd.append('file', file)//添加file表单数据
		      let url = this.IpConfig + '/xing/jtGongLuShouFeiZhan/upload'
		      this.$ajax({
		        method: 'post',
		        url: url,
		        data: fd,
		        headers: {
		          'Content-Type':
		            'multipart/form-data;boundary=' + new Date().getTime(),
		        },
		      })
		        .then((rsp) => {
		          console.log(rsp)
		          let resp = rsp.data
		          if (rsp.status == 200) {
		            that.fileList = []
		            that.visible = false
		            that.confirmLoading = false
		            that.$message.success('文件上传成功!')
		            this.spinning = false
		          } else {
		            this.$message.error('文件上传失败!')
		            that.visible = true
		          }
		        })
		        .catch((error) => {
		          this.$message.error('请求失败! error:' + error)
		          this.spinning = false
		          that.visible = true
		        })
		      return false
		    }
	    }
    }
</script>

二、Ant Design React文件上传功能

1.文件上传选项框

render() {
        const upLoad = {
            name: 'files',
            action: 'http://192.168.0.102:7072/folder/annex/upload',//文件上传地址
            headers: {
                authorization: 'authorization-text',
            },
            onChange: this.handleChange.bind(this),//上传文件改变时的状态
            showUploadList: false,//是否展示文件列表
        }
        const { page, pages, fileType } = this.state;

        return (<React.Fragment>
        		<div className={styles.tableBtnBox}>
                            <Button disabled={this.state.showBtn} type="primary">新建</Button>
                            <Button 
	                            disabled={this.state.showBtn} //是否可用
	                            onClick={this.onUpload.bind(this)} //点击方法
	                            className={styles.uploadBtn} //样式
	                            type="primary"
	                            ghost
                             	>上传</Button>
                        </div>
                        
						<Modal
                            title="文件上传"
                            visible={this.state.uploadState}//是否显示
                            onOk={this.handleOk.bind(this)}//确认方法
                            onCancel={this.handleCancel.bind(this)}//取消方法
                        >
                            <Dragger {...upLoad}>
                                <p className="ant-upload-drag-icon">
                                    <InboxOutlined />
                                </p>
                                <p className="ant-upload-text">单击或拖动文件到此区域以上传</p>
                            </Dragger>,
                		</Modal>
                		
                </React.Fragment>)
      }

效果:

Ant Design Upload文件上传功能怎么实现

2. js实现代码

//点击上传按钮方法
   onUpload() {
           this.setState({
               uploadState: true,
           })
       }

   //文件上传
   handleChange(info) {
       var fileSize = info.file.size;
       if (info.file.status === 'done') {
           if (info.file.response.code === 500) {
               message.error('上传文件失败');
               return
           }
           let response = info.file.response.res[0];
           if (response.suffix == 'xlsx' || response.suffix == 'docx' || response.suffix == 'pdf') {//当文件类型是xlsx,docx,pdf三种格式时
               let userid = Number(localStorage.getItem('userid'));
               const baseUrl = 'http://192.168.0.123:8889';
               const api = '/zhyjxxzhpt/file/upload';
               let fd = new FormData();//表单格式
               fd.append("userid", userid);//添加userid数据
               fd.append("id", response.id);//添加id数据
               fd.append("name", response.name);//添加name数据
               fd.append("suffix", response.suffix);//添加suffix数据
               fd.append("type", response.type);//添加type数据
               axios({
                   url: baseUrl + api,//文件数据保存的地址
                   method: "post",
                   data: fd,
                   headers: {
                       "Content-Type": "multipart/form-data;boundary=" + new Date().getTime()
                   }
               }).then(res => {
                   if (res.data.code == 'success') {
                       message.success(`${response.name} 文件上传成功!`);
                   }

                   this.queryPrivate();

               })
           } else {
               message.error(`只能上传xlsx,docx,pdf文件!`);
               return false
           }

       } else if (info.file.status === 'error') {
           if (fileSize > 1048576) {
               message.error(`${info.file.name}文件大于1M!`);
           } else {
               message.error(`${info.file.name} 文件上传失败!`);
           }

       }
   }
//点击确定按钮方法
   handleOk = e => {
       this.setState({
           uploadState: false,
       });
   };
//取消方法
   handleCancel = e => {
       this.setState({
           uploadState: false,
       });
   };

以上就是“Ant Design Upload文件上传功能怎么实现”这篇文章的所有内容,感谢各位的阅读!相信大家阅读完这篇文章都有很大的收获,小编每天都会为大家更新不同的知识,如果还想学习更多的知识,请关注亿速云行业资讯频道。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI