Vue+SpringBoot图片上传和下载

本方法是使用el-upload上传文件至本地文件夹中,再用WebMvcConfigurer对匹配的URL进行拦截,映射到本地文件夹来展示和下载图片。

el-upload实现图片回显:

template页面显示部分:

      <el-form-item label="头像">
        <el-upload class="avatar-uploader"
                   :show-file-list="false"
                   :action="uploadUrl"
                   :headers="tokenInfo"
                   ref="upload"
                   :on-success="handleAvatarSuccess">
          <img v-if="dataForm.imgUrl"
               :src="dataForm.imgUrl"
               class="avatar">
          <i v-else
             class="el-icon-plus avatar-uploader-icon"></i>
        </el-upload>
      </el-form-item>

js部分:

export default {
  data () {
    return {
      visible: false,
      file: null,
    }
  }
}
  methods: {
    handleAvatarSuccess (raw,file) {
      this.dataForm.imgUrl = URL.createObjectURL(file.raw)
    }
}

上传图片后通过URL.createObjectURL()方法生成一个图片URL,并将img标签的src属性指向这个URL

编写配置类:

首先建立配置类继承WebMvcConfigurer并重写addResourceHandlers方法:

@Configuration
public class MyWebMvcConfig implements WebMvcConfigurer {

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        String filePath = System.getProperty("user.dir") + "/src/main/resources/static/img/";
        System.out.println(filePath);
        registry.addResourceHandler("/static/**")
                .addResourceLocations("file:" + filePath);
        //addResourceHandler()里的是虚拟路径,addResourceLocations()里加的是真实路径
        WebMvcConfigurer.super.addResourceHandlers(registry);
    }
}

addResourceHandler()里的是虚拟路径,addResourceLocations()里加的是真实路径

然后在本地文件夹里添加一张图片,启动项目测试能否成功显示图片;

可见,通过虚拟路径映射成功显示本地图片,开始下一步操作。

后端保存图片信息

后端控制器:

    @PostMapping("/upload")
    public R upload(@RequestParam("file") MultipartFile file) throws IOException {

        String fileName = file.getOriginalFilename();
        String hToken = UUID.randomUUID().toString();
        String HeadName = hToken + fileName;
        String filePath = System.getProperty("user.dir") + "/src/main/resources/static/img/";
        String fileAddress = filePath + HeadName;  //文件真实路径
        try {
            file.transferTo(new File(fileAddress));

        } catch (Exception e) {
        }
        return R.ok().put("url", "http://localhost:8080/static/" + HeadName);
        //文件映射路径
    }

保存文件到静态目录下,并返回该文件映射路径;

前端代码:

export default {
  data () {
    return {
      uploadUrl: this.$http.adornUrl('/tb/img/upload'),
        }
    }
}
methods: {
    handleAvatarSuccess (res, file) {
      this.dataForm.imgUrl = URL.createObjectURL(file.raw)
      this.dataForm.img = res.url
    }
}

将返回的映射路径保存到表单中以待后续处理。

前端展示图片,下载图片

前端页面代码:

      <el-table-column label="图片"
                       v-bind="dataList.img"
                       header-align="center"
                       align="center">
        <template slot-scope="scope">
          <img :src="scope.row.imgUrl"
               class="avatar-navbar"
               v-if="scope.row.imgUrl">
        </template>
          <el-button type="text"
                     size="small"
                     @click="download(scope.row.imgUrl,scope.row.imgName)">下载</el-button>
      </el-table-column>
        

这里的imgUrl就是上面返回的url

前端js代码:

methods: {
    download (url, fileName) {
      this.$http({
        url: this.$http.adornUrl('/common/download'),
        method: 'post',
        responseType: 'blob',
        params: {
          'url': url,
          'name': fileName,

        }
      }).then(res => {
        console.log(res)
        if (res.data.size > 0) {
          var blob = new Blob([res.data]);
          var href = URL.createObjectURL(blob);
          var downloadElement = document.createElement('a');
          downloadElement.href = href;
          downloadElement.download = fileName + "." + 'JPG'; // 下载后文件名
          document.body.appendChild(downloadElement);
          downloadElement.click(); // 点击下载
          document.body.removeChild(downloadElement); // 下载完成移除元素
          window.URL.revokeObjectURL(href); // 释放掉blob对象
        } else {
          this.$message.error('文件或图片失效请重新上传')
        }
      });
    },

最后运行效果

  • 1
    点赞
  • 13
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
首先,你需要使用 ElementUI 中的 Upload 组件来实现图片上传。具体步骤如下: 1. 在 Vue 组件中引入 ElementUI 的 Upload 组件: ``` <template> <el-upload class="upload-demo" action="/api/upload" :on-success="handleSuccess" :before-upload="beforeUpload" :limit="1" :file-list="fileList" :auto-upload="false"> <el-button slot="trigger" size="small" type="primary">选取文件</el-button> <el-button style="margin-left: 10px;" size="small" type="success" @click="submitUpload">上传到服务器</el-button> <div slot="tip" class="el-upload__tip">只能上传jpg/png文件,且不超过500kb</div> </el-upload> </template> ``` 2. 在 Vue 组件中定义上传文件的处理函数 handleSuccess: ``` <script> export default { data() { return { fileList: [] }; }, methods: { handleSuccess(response, file, fileList) { console.log(response); this.fileList = fileList; }, beforeUpload(file) { const isJPG = file.type === "image/jpeg" || file.type === "image/png"; const isLt500K = file.size / 1024 < 500; if (!isJPG || !isLt500K) { this.$message.error("上传图片只能是 JPG/PNG 格式,且不超过 500KB"); } return isJPG && isLt500K; }, submitUpload() { this.$refs.upload.submit(); } } }; </script> ``` 3. 在后端 SpringBoot 中编写上传文件的 API: ``` @RestController @RequestMapping("/api") public class FileUploadController { @PostMapping("/upload") public ResponseEntity<?> uploadFile(@RequestParam("file") MultipartFile file) { try { // 存储文件 byte[] bytes = file.getBytes(); Path path = Paths.get("uploads/" + file.getOriginalFilename()); Files.write(path, bytes); // 返回成功信息 return ResponseEntity.ok("File uploaded successfully"); } catch (IOException e) { e.printStackTrace(); return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build(); } } } ``` 4. 在前端 Vue 中设置上传文件的 API 地址为后端 SpringBoot 中编写的 API 地址: ``` <el-upload class="upload-demo" action="/api/upload" :on-success="handleSuccess" :before-upload="beforeUpload" :limit="1" :file-list="fileList" :auto-upload="false"> ... </el-upload> ``` 这样,你就可以在前端使用 ElementUI+Vue 实现图片上传,并在后端使用 SpringBoot 接收上传的图片文件了。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值