上传文件(vue3)

使用el-upload  先上传到文件服务器,生成url

然后点击确定按钮: 保存数据 

<template>
  <el-dialog top="48px" width="500" title="新增协议" :modelValue="visible" @close="handleClose()">
    <div class="form-main">
      <el-form
        ref="ruleFormRef"
        :model="ruleForm"
        label-width="90px"
        class="demo-ruleForm"
        status-icon
      >
        <el-form-item
          label="协议名称: "
          prop="agreementName"
          :rules="[
            {
              required: true,
              message: '请输入协议名称',
              trigger: 'blur'
            },
            {
              message: '最多20个字符',
              trigger: 'blur',
              max: 20
            }
          ]"
        >
          <el-input v-model="ruleForm.agreementName" placeholder="请输入协议名称" />
        </el-form-item>
        <el-form-item
          label="协议文件: "
          prop="fileUrl"
          :rules="{
            required: true,
            message: '请选择协议文件',
            trigger: 'blur'
          }"
        >
          <div>
            <el-upload
              ref="uploadRef"
              class="upload-demo"
              :on-change="beforeUpload"
              :auto-upload="false"
              :show-file-list="false"
            >
              <template #trigger>
                <div class="upBtn">{{ fileName == "" ? "协议文件" : fileName }}</div>
              </template>
              <div class="div-desc">支持上传pdf文件</div>
            </el-upload>
          </div>
        </el-form-item>
      </el-form>
    </div>
    <template #footer>
      <el-button @click="handleClose()">取消</el-button>
      <el-button type="primary" @click="confirm(ruleFormRef)">确定</el-button>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import type { FormInstance } from "element-plus"
import { addAgreementManage } from "@/api/agreementManage"
import { uploadFile } from "@/api/common"
import { uploadCodeStr } from "@/types/common"
defineProps({
  visible: {
    type: Boolean,
    default: false
  }
})
const ruleFormRef = ref<FormInstance>()
const ruleForm = ref({
  agreementName: "",
  fileUrl: ""
}) as any
const emits = defineEmits(["closeDialog"])
const handleClose = (getData?: any) => {
  ruleForm.value = {
    agreementName: "",
    fileUrl: ""
  }
  fileName.value = ""
  nextTick(() => {
    ruleFormRef.value?.resetFields()
  })
  emits("closeDialog", getData ? true : false)
}
// 确定按钮
const confirm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  await formEl.validate((valid, fields) => {
    if (valid) {
      addAgreementManage({
        agreementName: ruleForm.value.agreementName,
        fileUrl: ruleForm.value.fileUrl
      }).then((res: any) => {
        if (res.code == 200) {
          ElMessage.success(res.msg)
          handleClose(true)
        } else {
          ElMessage.error(res.msg)
        }
      })
    } else {
      console.log("error submit!", fields)
    }
  })
}
// 上传文件
const beforeUpload = (file: any) => {
  // 判断文件类型
  const isPDF = file.raw.type === "application/pdf"
  if (!isPDF) {
    ElMessage.error("上传文件只能是 PDF 格式!")
    return
  }
  const isLt2M = file.size / 1024 / 1024 < 10
  if (!isLt2M) {
    ElMessage.error("上传文件大小不能超过 10MB!")
    return
  }
  upload(file)
}
let fileName = ref("")
// 上传文件
const upload = async (file: any) => {
  try {
    let { code, data } = await uploadFile({
      multipartFile: file.raw,
      code: uploadCodeStr
    })
    if (code && code == 200) {
      ruleForm.value.fileUrl = data.relativePath
      nextTick(() => {
        ruleFormRef.value?.validate()
      })
      fileName.value = file.raw.name
    } else {
      ElMessage.error("上传失败")
    }
  } catch (error) {
    // ElMessage.error("上传失败")
  }
}
</script>

<style scoped lang="scss">
.form-main {
  .upBtn {
    color: #409eff;
    cursor: pointer;
  }
}
.div-desc {
  width: 100%;
  color: #909399;
  font-size: 12px;
  margin-top: -10px;
}
</style>

二 查看协议

因为是个URL 直接打开就可以

  /**
   * 预览协议
   */
  const goPreview = (row: any) => {
    //新页面打开
    window.open(row.fileUrl)
    // window.open(configLlocation.filePathUrl + row.fileUrl)
  }

### 实现 Vue3Element Plus 的 Android 文件上传功能 为了在 Vue3 中使用 Element Plus 实现文件上传功能,可以按照以下方法操作: #### 1. 安装依赖项 首先,在项目中安装 `element-plus` 及其必要的依赖项。运行以下命令来完成安装: ```bash npm install element-plus ``` 如果需要支持移动端适配或其他特定需求,还可以额外引入样式库或工具。 #### 2. 配置 Element Plus 在项目的入口文件(通常是 `main.js` 或 `main.ts`)中配置并注册 Element Plus 组件: ```javascript import { createApp } from &#39;vue&#39;; import App from &#39;./App.vue&#39;; import ElementPlus from &#39;element-plus&#39;; import &#39;element-plus/dist/index.css&#39;; const app = createApp(App); app.use(ElementPlus); app.mount(&#39;#app&#39;); ``` 这一步确保了整个应用都可以访问到 Element Plus 提供的组件和样式[^1]。 #### 3. 使用 `<el-upload>` 组件实现文件上传 Element Plus 提供了一个名为 `<el-upload>` 的组件用于处理文件上传逻辑。以下是具体代码示例: ```vue <template> <div class="upload-container"> <el-upload :action="uploadUrl" :headers="headers" :on-success="handleSuccess" :before-upload="beforeUpload" multiple accept=".jpg,.png,.pdf" > <el-button type="primary">点击上传</el-button> </el-upload> <!-- 显示已上传文件 --> <ul v-if="fileList.length > 0"> <li v-for="(file, index) in fileList" :key="index">{{ file.name }}</li> </ul> </div> </template> <script> export default { data() { return { uploadUrl: &#39;https://example.com/upload&#39;, // 替换为目标服务器地址 headers: { Authorization: &#39;Bearer your_token_here&#39;, }, fileList: [], // 存储成功上传文件列表 }; }, methods: { handleSuccess(response, file, fileList) { this.fileList.push(file); // 将新上传成功的文件加入列表 console.log(&#39;File uploaded successfully:&#39;, response); }, beforeUpload(file) { const isLt2M = file.size / 1024 / 1024 < 2; // 检查文件大小是否小于2MB if (!isLt2M) { this.$message.error(&#39;文件大小不得超过 2MB!&#39;); } return isLt2M; }, }, }; </script> <style scoped> .upload-container { margin-top: 20px; } </style> ``` 上述代码实现了以下几个核心功能: - **指定上传目标 URL**: 设置 `:action` 属性指向后端接收文件的服务接口。 - **设置请求头**: 如果服务端需要身份验证,则可以通过 `:headers` 添加认证令牌。 - **自定义校验规则**: 方法 `beforeUpload` 负责检查文件合法性,例如限制文件类型或大小[^2]。 - **响应事件监听**: 当文件上传完成后触发回调函数 `handleSuccess` 更新状态。 #### 4. 移动端兼容性优化 对于 Android 设备上的用户体验改进,建议采取如下措施: - 确保页面布局适应不同屏幕尺寸,可借助 CSS 媒体查询或者第三方框架如 Vant 来增强移动设备的支持能力。 - 测试实际环境下的文件选择器行为差异,并调整参数满足业务场景的需求。 --- ###
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值