Vue 和 Taro input type=“file“ 原生上传图片

1. 在vue3中可以 让 input 完全覆盖 自定义新按钮,并将 input 透明度设为0. 这样用户看到的是 自定义的按钮,但是实际上点击的是 input. 代码如下:

<div style="position: absolute;z-index: 999;opacity: 0;">
    <input
        type="file"
        accept="image/png,image/jpeg,image/gif"
        @change="handleFileChange($event)"
     />
</div>

<nut-button style="background-color: #5232b7;color: #fff;width: 100%;height: 40px;font-size: 16px;" size="small"
>立即上传</nut-button>

2. 提取file

const handleFileChange = async (event) => {

  const file = event.target.childNodes[0].files[0];

};

3.根据自己的项目逻辑,进行后续的处理。

4. 注意 使用原生 input type="file",上传只能上传一次。

解决如下:

vue3

(1)安装 jquery 

npm install jquery --save

(2)在vite.config.js中添加

configureWebpack: {
      plugins: [
        new webpack.ProvidePlugin({
          jQuery: 'jquery',
          'windows.jQuery': 'jquery',
        }),
      ],
      externals: {
        './cptable': 'var cptable',
      },
      resolve: { fallback: { fs: false } },
    },

(3)在使用的目录中引入

import $ from 'jquery'
Taro框架

(1)安装:

npm i @tarojs/extend

(2)在使用的目录中引入

import { $ } from '@tarojs/extend'

5. 然后在图片上传完以后添加如下代码:

$('input[type="file"]').val(null);

到此为止 input type="file",上传只能上传一次 的问题,就已经解决啦~ 

猜你喜欢

转载自blog.csdn.net/aidhdjdi/article/details/142924023
今日推荐