Vue upload 文件上传 , 预览(打开新窗口预览图片)

本文档展示了如何使用AntDesign of Vue组件库实现图片上传功能,包括设置上传参数、自定义上传请求、文件预览及图片转换为Base64。通过`<a-upload>`组件结合`custom-request`属性,可以实现与后端接口的交互,并通过`handlePreview`方法处理图片预览。同时,提供了文件上传成功后的处理逻辑,以及图片预览的弹窗实现。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

上传: 这里以Ant Design of Vue 为例



 <a-upload :file-list="fileList" action="#" accept=".png" :custom- request="handleUpload3"  @preview="handlePreview" :showUploadList="false">
   <a-button> <a-icon type="upload"></a-icon> 上传 </a-button>
 </a-upload>
//图片预览弹框
<a-modal :visible="previewVisible" :footer="null" @cancel="handleCancel">
      <img alt="example" style="width: 100%" :src="previewImage" />
</a-modal>

// fileList:[]    上传的文件

// action="#"     上传地址

// accept='.jpg'  上传类型

// custom-request 自定义上传方法

// @preview: 文件预览

// showUploadList: 是否显示上传后列表

// Headers: { 'content-type': 'multipart/form-data' } 设置上传的请求头部 

  // 上传
    async handleUp(file) {
      const fileData = new FormData();
      fileData.append('file', file.file);
      const res = await this.$axios.post('/sys-storage/upload', fileData, {
        Headers: { 'content-type': 'multipart/form-data' },
      });
     
      if (!res.status) file.onError();
      file.onSuccess();
      const files = res.data;  //upload 上传成功后的数据
      let params = {   // 接口参数 
        token: files.fileToken,
        pId: '',
        name: files.fileName, 
      };
      this.$axios.post(params).then(res => {
        // 调用后端上传接口存储信息
        if (res.status) {console.log('上传成功')}
      });
    },
 // 预览
  async handlePreview(file) {
      if (!file.url && !file.preview) {
        file.preview = await this.getBase64(file.originFileObj);
      }
      this.previewImage = file.url || file.preview; // 图片地址赋值
      this.previewVisible = true;    //预览弹框打开
    },

   getBase64(file) {
      return new Promise((resolve, reject) => {
        const reader = new FileReader();
        reader.readAsDataURL(file);
        reader.onload = () => resolve(reader.result);
        reader.onerror = error => reject(error);
      });
    },
//打开新窗口预览图片
 const imgWindow = window.open('');
 imgWindow && imgWindow.document.write(`<image src='${图片地址}' style='display: flex; margin: 0 auto'/>`);

### 实现 el-upload 文件预览功能 在 Vue 和 Element UI 中,`<el-upload>` 组件本身并不直接提供文件预览的功能。然而可以通过自定义逻辑来实现这一需求。以下是具体的解决方案: #### 自定义 `before-upload` 方法处理文件预览 可以利用 `<el-upload>` 的 `before-upload` 钩子函数拦截文件上传操作,在此阶段执行文件预览逻辑。 当用户选择文件时,可以在前端读取该文件的内容并显示其部分内容作为预览。对于图片类型的文件可以直接生成 Base64 编码用于展示;而对于其他类型的文件(如 Excel 或 PDF),则可能需要借助第三方库解析内容后再渲染到页面上。 ```javascript methods: { beforeUpload(file) { const fileType = file.type; // 判断是否为图片类型文件 if (['image/jpeg', 'image/png'].includes(fileType)) { this.previewImage(file); return false; // 返回false阻止默认上传行为 } // 对于非图片类文档可扩展更多支持格式 如Excel/PDF等 else if (fileType === 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet') { this.previewExcel(file); return false; } alert('Unsupported File Type'); return false; }, previewImage(file){ let reader = new FileReader(); reader.onloadend = () => { window.open(reader.result, '_blank'); // 打开新窗口查看大图 }; reader.readAsDataURL(file); }, previewExcel(file){ import('@/vendor/ReadXlsx').then(module =>{ // 假设已封装好xlsx解析工具模块 module.default(file).then(data=>{ console.log("excel data:",data); this.$alert(JSON.stringify(data), 'Preview Content',{ dangerouslyUseHTMLString:true, confirmButtonText:'OK' }); }) }) } } ``` 上述代码片段展示了如何基于不同文件类型调用不同的预览方式[^1] 。其中针对图像采用了简单的 base64 转换后打开链接的方式完成预览;而 excel 表格则是加载了一个异步导入的 xlsx 解析器插件,并将其结果显示在一个对话框里供用户查阅。 需要注意的是,由于当前使用的 element-ui 版本较低(v1.4.3),某些高级特性或许无法正常工作,因此建议升级至最新稳定版本以便获得更好的兼容性和用户体验改进[^2] 。 另外值得注意的一点就是关于跨域资源共享(CORS)问题 ,如果服务器端未设置允许访问资源,则可能会遇到权限错误的情况发生。此时需联系后台开发人员调整相应配置策略以满足实际业务场景的需求[^3] 。 最后提醒一下安全方面考虑因素 :始终要验证来自客户端的一切输入数据的有效性以及合法性以防恶意攻击者利用漏洞危害系统整体安全性!
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值