vue和react上传文件方法

最近的项目碰到了上传文件的需求,是用react做的,之前用vue做过类似的,react的试了一下差不太多
上传文件的整体流程是一样的,基本可分为
1.获取文件上传input的dom
2.新建FormData,将文件以后端约定的字段append至新建的FormData中
3.发送请求将该FormData发送至后端
整体流程就是这样,不过vue和react获取dom的方法有一点区别,这里分别作了整理

Vue

vue获取dom元素使用的是ref和this.$refs

<template>
	<input type="file" ref="upload" accept=".xlsx" @change="uploadFile" />
</template>
// this.$refs.upload 就是这个input的dom节点

获取dom节点后,通过该节点拿到文件,然后发送

uploadFile(){
	let formData = new FormData();
    formData.append("file", this.$refs.upload.files[0]);
    // formData.append("name", 'xz');
    // 如有需要,可以加入其他字段的数据
    
    // 发送网络请求,要注意设置Content-Type为multipart/form-data
    // 这里以axios作为示例
    axios.post("data/upload_file/", formData, {
          "Content-Type": "multipart/form-data"
        }).then(res=>{})
}

React

react中获取dom节点使用的是createRef()方法,创造一个refs,然后通过ref属性挂载至dom节点上,然后通过生成的refs来访问dom节点

import React, { Component } from 'react';
constructor(props) {
    super(props);
    this.upload = React.createRef();
}

class Upload extends Component {
    render() {
        return (
            <div>
				<input type="file" ref={this.upload} onChange={this.handleUpload} / >
            </div>
        );
    }
    // this.upload.current就是这个input的dom节点

获取dom节点后,整个流程就与vue没有太大的差别了

 handleUpload = () => {
    // console.log(this.upload.current);
    let formData = new FormData();
    formData.append("avatar", this.upload.current.files[0]);
	axios({
	method: "post",
    url: "users/upload_avatar",
    headers: {
      "Content-Type": "multipart/form-data"
    },
    data: formData,
	}).then(res=>{})
  };
  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值