vue实现input file上传图片 显示预览图

 

<template>
  <div>
    <input v-show="false" type="file" accept="image/*" @change="tirggerFile($event)" ref="input" />
    <div style="width:200px;height:200px;border:1px solid;text-align:center;" @click="openImg">
      <span v-if="imgUrl==''">点击上传</span>
      <img style="height:100%;width:100%;" v-if="imgUrl!=''" :src="imgUrl" />
    </div>
  </div>
</template>
export default {
  data() {
    return {
      isSelectFile: false,
      imgUrl: ""
    };
  },
  methods: {
    tirggerFile: function(event) {
      let file = event.target.files[0];
      let url = "";
      var reader = new FileReader();
      reader.readAsDataURL(file);
      let that = this;
      reader.onload = function(e) {
        url = this.result.substring(this.result.indexOf(",") + 1);
        that.imgUrl = "data:image/png;base64," + url;
        // that.$refs['imgimg'].setAttribute('src','data:image/png;base64,'+url);
      };
    },
    openImg() {
      this.$refs.input.click();
    }
  }
};
</script>

实现的效果:

具体的css样式可以自行发挥

  • 1
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
以下是基于SSM和Vue实现图片上传预览的代码示例: 前端代码: ``` <template> <div> <input type="file" ref="fileInput" accept="image/*" @change="handleFileUpload"> <img v-if="imageUrl" :src="imageUrl" style="max-width: 100%;"> </div> </template> <script> export default { data() { return { imageUrl: '', file: null } }, methods: { handleFileUpload() { this.file = this.$refs.fileInput.files[0]; this.previewImage(this.file); this.uploadFile(this.file); }, previewImage(file) { const reader = new FileReader(); reader.readAsDataURL(file); reader.onload = e => { this.imageUrl = e.target.result; } }, async uploadFile(file) { const formData = new FormData(); formData.append('file', file); try { const response = await this.$axios.post('/upload', formData); console.log(response.data); } catch (error) { console.log(error); } } } } </script> ``` 后端代码: ``` @Controller public class UploadController { @PostMapping("/upload") @ResponseBody public String upload(@RequestParam("file") MultipartFile file) throws IOException { // 保存文件到服务器 File uploadFile = new File("/path/to/upload/" + file.getOriginalFilename()); file.transferTo(uploadFile); // 返回文件访问路径 return "http://your.domain.com/upload/" + file.getOriginalFilename(); } } ``` 其中,前端代码使用了Vue.js框架和axios库,后端使用了Spring MVC框架。在前端,我们使用`<input type="file">`元素来让用户选择上传的片文件,然后使用FileReader API来预览片;在上传文件时,我们将文件封装为FormData对象,并使用axios库发送POST请求到后端的/upload接口;在后端,我们使用Spring MVC框架的@RequestParam注解来接收上传的文件,并将文件保存到服务器上,最后返回文件的访问路径。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值