node+vue+element实现简单的图片上传跟预览

本文档展示了如何使用Vue.js、Element UI和Node.js后端实现图片上传和预览功能。前端部分利用Element的上传组件处理文件上传,并通过axios发送POST请求到后端。后端接收到请求后将文件存储,并返回文件名。预览功能通过表格展示图片名称,点击后通过PDF组件显示图片。整个流程涉及前端组件交互、axios请求、后端文件处理和图片预览。

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

node+vue+element实现简单的图片上传跟预览

前端(分组件写的)
新建vendor文件夹跟index.vue

<template>
  <div>
    <div>
      <el-upload
        :show-file-list="false"
        :http-request="upload.bind(this)"
        action=""
      >
      上传文件
      </el-upload>
      <el-button @click="btnClick">查看</el-button>
    </div>
    <martreFileList v-if="martreNewFileList" :martersList="martersList"></martreFileList>
  </div>
</template>

<script>
import axios from "axios"
import martreFileList from '../martreFileList/imdex'
export default {
  data() {
    return {
      resultData: [],
      martreNewFileList:false,
      martersList:[]
    };
  },
  methods: {
  // 使用element-ui组件 实现文件上传
    upload(file,fileList){
      let arrnewList  = []
      let forms = new FormData();
      arrnewList.unshift(file.file);
      arrnewList.forEach((element) => {
        forms.append("file", element);
      });
      axios.post('http://localhost:3000/uploading',forms,{
        headers: {
          "Content-Type": "multipart/form-data",
        },
      }).then(res=>{
        if(res.data.ok){
          this.$nextTick(_=>{
            this.martersList.unshift(res.data)
          })
        }
      })
    },
    btnClick(){
      this.martreNewFileList = true
    }
  },
  components:{
    martreFileList
  },

};
</script>

<style lang="less">
</style>

新建martreFileList文件夹跟index.vue

// 用表格的方法是分单图片跟多图片(未写多文件)
<template>
  <div>
    <el-table 
      :data="martersList"
    >
      <el-table-column
        label="图片名字"
        prop="filename"
      >
      </el-table-column>
      <el-table-column label="查看"
      >
        <template slot-scope="scope">
          <span @click="showFile(scope.row)">查看</span>
        </template>
      </el-table-column>
    </el-table>
    <pdf v-if="srcImage" :srcResult="src" ref="pdf"></pdf>
  </div>
</template>

<script>
import axios from 'axios'
import pdf from '../pdf'
  export default {
    data() {
      return {
        src:null,
        srcImage:false
      }
    },
    props:["martersList"],
    components:{
      pdf
    },
    methods:{
      showFile(row){
        this.srcImage = true
        axios.post("http://localhost:3000/showFile",{
          params:row.filename
          //responseType:"arraybuffer"
        }).then(res=>{
          if(res.data.ok){
            this.$nextTick(_=>{
            this.$refs.pdf.printVisible = true
            this.src = res.data.srcImage
            })
          }
        })
      }
    }
  }
</script>
<style lang="less" scoped>
span{
  cursor: pointer;
}
</style>

新建pdf文件夹建立index.vue

// 形成弹窗的样子返回
<template>
  <div>
     <el-dialog :visible.sync="printVisible"
      :close-on-click-modal="false" :show-close="false"
     >
        <img :src="srcResult" alt="">
     </el-dialog>
  </div>
</template>
<script>
  export default {
    props:['srcResult'],
    data() {
      return {
        printVisible:false
      }
    },
  }
</script>
<style lang="less" scoped>
</style>

node 后端

// 文件上传
app.post("/uploading", (req, res) => {
  if (!fs.existsSync('./public/image')) {
    fs.mkdirSync('./public/image', {
      recursive: true
    });
  }
  let form = new multiparty.Form({uploadDir:'./public/image'}) // 设置文件储存目录
    form.parse(req, (err, field , files) => {
      console.log(files.file)
      files.file.map(ele=>{
        fs.rename(ele.path, './public/image/' + ele.originalFilename,()=>{
          let pic = {filename:ele.originalFilename}
          res.json({filename:pic.filename,ok:true,})
      })
    })
  })
})

图片查看

app.post('/showFile',(req,res)=>{
 let image = req.body.params
 res.json({srcImage: `http://localhost:3001/public/image/${image}`,ok:true})
//  let image = req.body.params // 转base64返回前端
// fs.readFile(`./public/image/${image}`,'binary',function(err,data){
//   if(err) throw err
//   else{
//     let bufferData = Buffer.from(data).toString("base64")
//     res.send(bufferData)   
//   }
// })
})
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值