vue 利用原生input上传图片并预览并删除

本文详细介绍了基于Vue的图片上传组件实现,包括如何通过监听文件输入事件实现图片预览、压缩及格式验证,并展示了如何使用Canvas进行图片压缩,以及如何在用户界面上实时更新图片预览效果。
<template>

  <div class="com-upload-img">

    <div class="img_group">

      <div v-if="allowAddImg" class="img_box">

        <input type="file" accept="image/*" multiple="multiple" @change="changeImg($event)">

        <div class="filter" />

      </div>

      <div v-for="(item,index) in imgArr" :key="index" class="img_box">

        <div class="img_show_box">

          <img :src="item" alt="">

          <i class="img_delete" @click="deleteImg(index)" />

          <!-- <i class="img_delete" @click="imgArr.splice(index,1)"></i> -->

        </div>

      </div>

    </div>

  </div>

</template>

js部分

<script>

export default {

  name: 'ComUpLoad',

  data() {

    return {

      imgData: '',

      imgArr: [],

      imgSrc: '',

      allowAddImg: true

    }

  },

  methods: {

    changeImg: function(e) {

      var _this = this

      var imgLimit = 1024

      var files = e.target.files

      var image = new Image()

      if (files.length > 0) {

        var dd = 0

        var timer = setInterval(function() {

          if (files.item(dd).type !== 'image/png' && files.item(dd).type !== 'image/jpeg' && files.item(dd).type !== 'image/gif') {

            return false

          }

          if (files.item(dd).size > imgLimit * 102400) {

            // to do sth

          } else {

            image.src = window.URL.createObjectURL(files.item(dd))

            image.onload = function() {

              // 默认按比例压缩

              var w = image.width

              var h = image.height

              var scale = w / h

              w = 200

              h = w / scale

              // 默认图片质量为0.7,quality值越小,所绘制出的图像越模糊

              var quality = 0.7

              // 生成canvas

              var canvas = document.createElement('canvas')

              var ctx = canvas.getContext('2d')

              // 创建属性节点

              var anw = document.createAttribute('width')

              anw.nodeValue = w

              var anh = document.createAttribute('height')

              anh.nodeValue = h

              canvas.setAttributeNode(anw)

              canvas.setAttributeNode(anh)

              ctx.drawImage(image, 0, 0, w, h)

              var ext = image.src.substring(image.src.lastIndexOf('.') + 1).toLowerCase()// 图片格式

              var base64 = canvas.toDataURL('image/' + ext, quality)

              // 回调函数返回base64的值

              if (_this.imgArr.length <= 4) {

                _this.imgArr.unshift('')

                _this.imgArr.splice(0, 1, base64)// 替换数组数据的方法,此处不能使用:this.imgArr[index] = url;

                if (_this.imgArr.length >= 5) {

                  _this.allowAddImg = false

                }

              }

            }

          }

          if (dd < files.length - 1) {

            dd++

          } else {

            clearInterval(timer)

          }

        }, 1000)

      }

    },

    deleteImg: function(index) {

      this.imgArr.splice(index, 1)

      if (this.imgArr.length < 5) {

        this.allowAddImg = true

      }

    }

  }

}

</script>

搬运

https://www.cnblogs.com/lst619247/p/10748724.html

<think> 根据用户需求,需要在Vue2中实现上传PDF文件进行预览的功能。结合提供的引用信息,我们可以总结出两种主要方法:使用iframe直接预览和使用vue-pdf组件。同时,引用[3]提到了Springboot+vue2的文件上传下载和pdf预览,但用户明确需求是Vue2中的实现,因此我们主要关注前端部分。 ### 方法一:使用iframe直接预览(简单易行) 这种方法通过`<input type="file">`上传文件,获取文件的本地URL(或服务器返回的URL),然后使用`<iframe>`标签来预览。 #### 步骤: 1. **上传文件**:使用`<input type="file">`选择PDF文件。 2. **获取文件URL**:使用`URL.createObjectURL`将文件对象转换为临时URL。 3. **预览**:在iframe中设置src为该临时URL。 #### 示例代码: ```vue <template> <div> <input type="file" @change="handleFileUpload" accept=".pdf"> <iframe v-if="pdfUrl" :src="pdfUrl" width="100%" height="600px"></iframe> </div> </template> <script> export default { data() { return { pdfUrl: null }; }, methods: { handleFileUpload(event) { const file = event.target.files[0]; if (file && file.type === 'application/pdf') { this.pdfUrl = URL.createObjectURL(file); } else { alert('请选择PDF文件'); } } }, beforeDestroy() { // 清理临时URL if (this.pdfUrl) URL.revokeObjectURL(this.pdfUrl); } }; </script> ``` ### 方法二:使用vue-pdf组件(更复杂但功能更强) 引用[2]提到使用`vue-pdf`组件,它基于PDF.js,支持更多功能(如分页、缩放等)。但需要注意跨域问题。 #### 步骤: 1. 安装依赖:`npm install vue-pdf --save` 2. 在组件中引入使用 #### 示例代码: ```vue <template> <div> <input type="file" @change="handleFileUpload" accept=".pdf"> <div v-if="pdfUrl"> <pdf :src="pdfSrc" @num-pages="pageCount = $event" @page-loaded="currentPage = $event"></pdf> <div>当前页: {{ currentPage }} / {{ pageCount }}</div> </div> </div> </template> <script> import pdf from 'vue-pdf'; export default { components: { pdf }, data() { return { pdfSrc: null, currentPage: 0, pageCount: 0 }; }, methods: { handleFileUpload(event) { const file = event.target.files[0]; if (file && file.type === 'application/pdf') { // 创建临时URL,使用vue-pdf的createLoadingTask包装 const url = URL.createObjectURL(file); this.pdfSrc = pdf.createLoadingTask(url); } } } }; </script> ``` ### 注意事项: 1. **跨域问题**:如果PDF文件来自其他域,可能会遇到跨域问题。解决方法: - 确保服务器设置正确的CORS头(如`Access-Control-Allow-Origin`)[^2]。 - 如果是本地文件,使用`vue-pdf`时可能需要将文件上传到服务器再预览。 2. **性能优化**:大文件预览时,可以考虑分页加载。 3. **临时URL清理**:使用`URL.createObjectURL`后,在组件销毁前需要调用`URL.revokeObjectURL`释放内存。 ### 总结 - 简单需求:使用iframe直接预览,无需额外依赖。 - 复杂需求(如分页、缩放):使用vue-pdf组件。 §§相关问题§§ 1. 在Vue2中如何处理PDF预览时的跨域问题? 2. 如何优化vue-pdf组件加载大型PDF文件的性能? 3. 除了iframe和vue-pdf,还有哪些Vue2的PDF预览方案? </think> ### Vue2中实现PDF文件上传预览的方法 在Vue2中实现PDF文件上传预览,主要有以下两种主流方法: #### 方法一:使用iframe直接预览(简单高效) ```vue <template> <div> <!-- 文件上传 --> <input type="file" @change="handleUpload" accept=".pdf"> <!-- PDF预览 --> <iframe v-if="pdfUrl" :src="pdfUrl" width="100%" height="600px" frameborder="0" ></iframe> </div> </template> <script> export default { data() { return { pdfUrl: null } }, methods: { handleUpload(event) { const file = event.target.files[0]; if (file && file.type === 'application/pdf') { // 创建临时URL预览 this.pdfUrl = URL.createObjectURL(file); // 实际项目中需上传到服务器 // const formData = new FormData(); // formData.append('pdf', file); // axios.post('/upload', formData)... } } }, beforeDestroy() { // 清理临时URL if (this.pdfUrl) URL.revokeObjectURL(this.pdfUrl); } } </script> ``` **优点**:原生支持,无需额外依赖 **缺点**:浏览器兼容性问题,功能较基础[^1] #### 方法二:使用vue-pdf组件(功能丰富) 1. 安装依赖: ```bash npm install vue-pdf ``` 2. 组件实现: ```vue <template> <div> <input type="file" @change="handlePreview" accept=".pdf"> <div v-if="showDialog"> <pdf :src="pdfSrc"></pdf> </div> </div> </template> <script> import pdf from 'vue-pdf' export default { components: { pdf }, data() { return { showDialog: false, pdfSrc: null } }, methods: { async handlePreview(event) { const file = event.target.files[0]; if (!file) return; // 处理跨域问题 [^2] const blobUrl = URL.createObjectURL(file); try { // 创建加载任务 this.pdfSrc = pdf.createLoadingTask(blobUrl); this.showDialog = true; } catch (error) { console.error('PDF加载失败:', error); } } } } </script> ``` **优点**:支持分页/缩放等高级功能 **注意点**: - 需要处理可能的跨域问题[^2] - 大文件需分页加载优化性能 - 安装后需重启开发服务器 #### 后端配合(Spring Boot示例) 如需保存文件,后端需配置接口: ```java @PostMapping("/upload") public ResponseEntity<String> uploadPdf(@RequestParam("file") MultipartFile file) { // 保存文件到服务器目录 String filePath = "/uploads/" + file.getOriginalFilename(); file.transferTo(new File(filePath)); return ResponseEntity.ok(filePath); } ``` 前端上传后使用返回的URL预览[^3]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值