Vue+SpringBoot将服务器端的图片,写到前端页面中

2021-01-23  本文已影响0人  Wannay

1.后端Controller

package com.example.demopro.controller.Upload;

import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.HashMap;
import java.util.Map;


@RestController
public class UploadController {
    //本机的文件路径
    //String pathname = "/Users/wanna/Desktop/blog/UserLoginDemo/Demo/demopro/src/main/resources/file/logo";
    //服务器的文件路径
    String pathname = "/java/file/logo";

    @RequestMapping(value = "/file/getlogo", method = RequestMethod.GET)
    public void GetLogo(HttpServletRequest request, HttpServletResponse response) throws IOException {
        //获取用户输入的用户名
        String username = SecurityContextHolder.getContext().getAuthentication().getName();
        String filename = "logo_" + username + ".jpg";  //根据用户名生成文件名

        File file = new File(pathname, filename);
        FileInputStream fis;
        fis = new FileInputStream(file);

        long size = file.length();
        byte[] data = new byte[(int) size];
        fis.read(data, 0, (int) size);
        fis.close();
        response.setContentType("image/png");
        OutputStream out = response.getOutputStream();
        out.write(data);
        out.flush();
        out.close();
    }

    @RequestMapping(value = "/file/upload/logo", method = RequestMethod.POST)
    public Map<String, Object> upload(MultipartFile file) throws IOException {
        Map<String, Object> map = new HashMap<>();
        if (file != null) {  //如果获取到的文件不为空
            String username = SecurityContextHolder.getContext().getAuthentication().getName();
            String filename = "logo_" + username + ".jpg";  //根据用户名生成文件名
            File file_server = new File(pathname, filename);  //创建文件对象
            if (!file_server.getParentFile().exists()) {
                //如果文件父目录不存在,就创建这样一个目录
                file_server.getParentFile().mkdirs();
                System.out.println("创建目录" + file);
            } else {  //如果父文件夹已经存在


            }
            if (file_server.exists()) {
                file_server.delete();  //如果这个文件已经存在了,删除掉,重新上传
            } else {

            }
            file.transferTo(file_server);
            map.put("status", true);
            map.put("msg", "上传文件成功");
        } else {   //如果获取到的文件为空
            map.put("status", false);
            map.put("msg", "上传文件失败");
            map.put("reason", "文件为空");
        }
        return map;
    }

}


2.前端读取

<template>
  <div id="blog_main">
    <div id="nav_main">
      <el-menu class="el-menu-demo" mode="horizontal" id="nav_items">
        <el-menu-item index="1" @click="WriteBlog">写博客</el-menu-item>
        <el-submenu index="2">
          <template slot="title">
            <img
              :src="logo_src"
              height="40px"
              width="40px"
              style="border-radius: 50%"
          /></template>
          <el-menu-item index="2-1" @click="UploadLogo()"
            >个人资料</el-menu-item
          >
          <el-menu-item index="2-2" @click="GetSelfBlog()"
            >我的文章</el-menu-item
          >
          <el-menu-item index="2-3">退出</el-menu-item>
        </el-submenu>
      </el-menu>
    </div>
    <div class="blog" v-for="blog in BlogList" :key="blog.id">
      <el-container>
        <el-header>
          <div
            v-html="blog.blog_title"
            @click="ToDetails(blog.id)"
            style="cursor: pointer"
          ></div
        ></el-header>
        <el-main><div v-html="blog.content"></div></el-main>
      </el-container>
      <el-divider />
    </div>
  </div>
</template>

<script>
import marked from "marked";
import request from "../network/request";
import { mavonEditor } from "mavon-editor";
import "mavon-editor/dist/css/index.css";
export default {
  components: {
    //注册组件
    mavonEditor,
  },
  data() {
    return {
      logo_src: "",
      token: "",
      BlogList: [],
    };
  },
  methods: {
    UploadLogo() {
      this.$router.push("/home");
    },
    WriteBlog() {
      //跳转到写博客界面
      this.$router.push("/writeblog");
    },
    ToDetails(blog_id) {
      //根据传递的参数查询后端数据库
      console.log(blog_id);
      this.$router.push({
        path: "blogdetails",
        query: {
          blog_id: blog_id,
        },
      });
    },
    GetSelfBlog() {
      this.$router.push("/myblogs");
    },
  },
  created() {
    //获取localStorage中的token信息(用来后端校验认证/授权)
    this.token = localStorage.getItem("token");
    request({
      //访问后端的blog_all的api,展示页面中的博客信息
      url: "/api/blog_all",
      method: "get",
      headers: {
        //在headers中传递token信息
        token: this.token,
      },
    })
      .then((res) => {
        console.log(res);
        var bloglist = res.data; //得到博客的列表
        for (var i = 0; i < bloglist.length; i++) {
          this.BlogList.push(bloglist[i]);
          //将内容部分的markdown转换为html
          this.BlogList[i].content = marked(this.BlogList[i].content);
        }
      })
      .catch((err) => {
        //请求失败打印失败信息
        console.log(err);
      });

    request({
      url: "/api/file/getlogo",
      headers: {
        token: localStorage.getItem("token"),
      },
      responseType: "arraybuffer",
    })
      .then((res) => {
        //将后端的图片转换为base64去显示
        this.logo_src =
          "data:image/png;base64," +
          btoa(
            new Uint8Array(res.data).reduce(
              (data, byte) => data + String.fromCharCode(byte),
              ""
            )
          );
        // console.log(res);
      })
      .catch((err) => {
        console.log(err);
      });
  },
};
</script>

<style>
.blog {
  margin-top: 25px; /* 设置每条博客之间的间隙 */
}

.el-header {
  background-color: #eeffee;
  color: #333;
  text-align: left;
  line-height: 60px;
}

.el-main {
  background-color: #eee;
  color: #333;
  text-align: left;
  /*line-height: 160px;*/
}

.blog > .el-container {
  margin-left: auto;
  margin-right: auto;
  margin-bottom: 40px;
  width: 1200px;
}

#nav_main_items {
  display: flex;
  flex-direction: row;
  justify-content: flex-end;
}

#nav_items {
  display: flex;
  flex-direction: row;
  justify-content: flex-end;
}
</style>

获取图片的关键代码为:

request({
      url: "/api/file/getlogo",
      headers: {
        token: localStorage.getItem("token"),
      },
      responseType: "arraybuffer",
    })
      .then((res) => {
        //将后端的图片转换为base64去显示
        this.logo_src =
          "data:image/png;base64," +
          btoa(
            new Uint8Array(res.data).reduce(
              (data, byte) => data + String.fromCharCode(byte),
              ""
            )
          );
        // console.log(res);
      })
      .catch((err) => {
        console.log(err);
      });

将后端传递的数据转换为arraybuffer,再转成base64,得到图片的src,使用img标签,添加src属性,并设为图片的src即可得到。

上一篇下一篇

猜你喜欢

热点阅读