iview Upload组件+egg实现图片预览上传回显

本文介绍了一个基于Vue.js的图片上传与预览组件的实现细节,包括如何处理文件格式错误、大小限制,以及如何使用FileReader API读取图片并显示大图。组件还包含了拖拽上传功能和自定义样式。

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

<div v-if="uploadImg.url" class="upload-img">
  <img :src="uploadImg.url">
  <div class="upload-img-cover">
    <Icon type="ios-eye-outline" @click.native="showBigImg = true"></Icon>
    <Icon type="ios-trash-outline" @click.native="uploadImg = {}"></Icon>
  </div>
</div>
<Upload
  ref="upload"
  :show-upload-list="false"
  :before-upload="handleUpload"
  type="drag"
  action=""
  style="display: inline-block;width:58px;">
  <div style="width: 58px;height:58px;line-height: 58px;">
    <Icon type="ios-camera" size="20"></Icon>
  </div>
</Upload>
<Modal title="查看大图" v-model="showBigImg">
  <img :src="uploadImg.url" style="width: 100%">
</Modal>
uploadImg: {},
showBigImg: false,
handleFormatError(file) {
  this.$Notice.warning({
    title: '文件格式不正确',
    desc: '文件 ' + file.name + ' 格式不正确,请上传 jpg、jpeg 或 png 的图片文件。',
  });
},
handleMaxSize(file) {
  this.$Notice.warning({
    title: '超出文件大小限制',
    desc: '文件 ' + file.name + ' 太大,不能超过 2M。',
  });
},
handleUpload(file) {
  if (file.type !== 'image/jpg' && file.type !== 'image/jpeg' && file.type !== 'image/png') {
    this.handleFormatError(file);
  } else if (file.size > 2 * 1024 * 1024) {
    this.handleMaxSize(file);
  } else {
    const reader = new FileReader();
    reader.readAsDataURL(file);
    reader.onloadend = () => {
      this.uploadImg = {
        url: reader.result,
        file,
      };
    };
  }
  return false;
},
const formData = new FormData();
for (const key in this.modalParams) {
  formData.append(key, this.modalParams[key]);
}
if (this.uploadImg.file) {
  formData.append('logo', this.uploadImg.file);
}
this.$axios._api_dashboard_service.post('', formData).then(res => {});
this.$axios._api_dashboard_service.get('', { params: {} }).then(res => {
  const result = res.data;
  if (result.status === 'SUCCEED') {
    const data = result.data;
    let url = '';
    if (data.url) {
      url = 'data:image/png;base64,' + data.url;
    }
    this.uploadImg = {
      url,
    };
  }
});
.upload-img{
  display: inline-block;
  width: 60px;
  height: 60px;
  text-align: center;
  line-height: 60px;
  border: 1px solid transparent;
  border-radius: 4px;
  overflow: hidden;
  background: #fff;
  position: relative;
  box-shadow: 0 1px 1px rgba(0,0,0,.2);
  margin-right: 4px;
}
.upload-img img{
  width: 100%;
  height: 100%;
}
.upload-img-cover{
  display: none;
  position: absolute;
  top: 0;
  bottom: 0;
  left: 0;
  right: 0;
  background: rgba(0,0,0,.6);
}
.upload-img:hover .upload-img-cover{
  display: block;
}
.upload-img-cover i{
  color: #fff;
  font-size: 20px;
  cursor: pointer;
  margin: 0 2px;
}

保存图片
requireFile: false 表明文件不是必传,此配置是在egg-multipart 2.1.0版本加入的,低版本会报错,须升级egg

// await-stream-ready, 文件读写流 ready 库,主要是方便的使用 await 进行文件上传, 否则可能出现数据丢失的情况
const awaitWriteStream = require('await-stream-ready').write;

const stream = await ctx.getFileStream({ requireFile: false });
ctx.validate(rule, stream.fields);
const body = stream.fields;
if (stream.filename) {
  if (!fs.existsSync(dir)) {
    fs.mkdirSync(dir);
  }
  const filePath = path.join(dir, filename);
  const writeStream = fs.createWriteStream(filePath);
  try {
    await awaitStreamReady(stream.pipe(writeStream));
  } catch (err) {
    await sendToWormhole(stream);
    throw err;
  }
} else {
  await sendToWormhole(stream);
}

获取图片的base64编码,用于回显

const filePath = path.join(dir, filename);
let url = '';
if (fs.existsSync(filePath)) {
  const data = fs.readFileSync(filePath);
  url = data.toString('base64');
}

删除图片

const filePath = path.join(dir, filename);
if (fs.existsSync(filePath)) {
  fs.unlinkSync(filePath);
}
<think>嗯,用户想了解iView Upload组件如何实现上传图片的本地预览。首先,我需要回忆iView(现在叫View Design)的上传组件的基本用法。记得Upload组件支持文件上传,并且可以通过设置属性来实现预览。 接下来,本地预览的关键应该是在选择文件后,不等待服务器响应就能图片。通常这需要用到FileReader API,将文件读取为DataURL。iViewUpload组件是否有内置的预览功能呢?查看文档,发现before-upload钩子可以用来处理文件,在这里可以读取文件并生成预览。 然后,用户可能需要代码示例。需要确保他们使用的是正确的属性,比如设置list-type为picture,并且使用before-upload来生成预览URL。同时,要记得在data中定义previewImage和previewVisible等变量,用于控制预览模态框的示。 还需要考虑手动触发预览,因为默认点击文件名可能不会图片。可能需要自定义on-preview事件,将预览图赋值给模态框,并示出来。此外,样式和模态框的关闭事件也需要处理,比如设置on-visible-change来隐藏预览。 可能遇到的问题包括跨浏览器的兼容性,FileReader的使用是否正确,以及图片路径是否正确绑定到组件的file-list。要提醒用户确保每个文件的url属性正确,这样组件才能正确预览图。 最后,是否需要分步骤说明?用户可能需要从引入组件、配置属性、处理预览逻辑到示模态框的完整流程。确保代码示例清晰,并解释关键部分的作用,比如before-upload的作用和FileReader的使用。</think>iView(现为 View Design)Upload 组件实现本地图片预览的步骤如下: ### 一、核心原理 通过 `before-upload` 钩子 + `FileReader` API 实现: 1. 选择文件时触发 `before-upload` 2. 用 `FileReader` 将图片转为 base64 格式 3. 手动更新 `file-list` 数据实现预览 ### 二、基础代码实现 ```vue <template> <Upload action="//jsonplaceholder.typicode.com/posts/" :before-upload="handlePreview" :file-list="fileList" list-type="picture" @on-remove="handleRemove"> <Button icon="ios-cloud-upload-outline">选择图片</Button> </Upload> </template> <script> export default { data() { return { fileList: [] } }, methods: { handlePreview(file) { return new Promise((resolve) => { const reader = new FileReader() reader.readAsDataURL(file) reader.onload = () => { this.fileList.push({ name: file.name, url: reader.result // 生成base64预览地址 }) resolve(false) // 阻止自动上传 } }) }, handleRemove(file) { const index = this.fileList.indexOf(file) this.fileList.splice(index, 1) } } } </script> ``` ### 三、关键配置说明 1. `list-type="picture"`:启用图片列表模式 2. `:file-list`:绑定响应式的文件列表数据 3. `before-upload`:上传前处理预览逻辑 4. `resolve(false)`:阻止自动提交到action地址 ### 四、扩展功能 - 大图预览 增加预览模态框: ```vue <template> <!-- 在Upload组件添加 --> @on-preview="handleImagePreview" <Modal v-model="previewVisible" title="预览" footer-hide> <img :src="previewImage" style="width: 100%"> </Modal> </template> <script> export default { data() { return { previewVisible: false, previewImage: '' } }, methods: { handleImagePreview(file) { this.previewImage = file.url this.previewVisible = true } } } </script> ``` ### 五、注意事项 1. 需要手动维护 `fileList` 的状态 2. 浏览器兼容性:IE10+ 支持 FileReader 3. 大文件建议做压缩处理(可配合 canvas) 4. 真实上传需在确认操作后手动调用上传接口 通过这种实现方式,可以在不依赖服务器响应的情况下,立即展示用户选择的本地图片预览效果。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值