使用

在vue项目中使用input上传图片给后台时,需要对图片文件流和请求头进行一些处理

1、获取上传图片文件流

<template>
  <div class="upload-file">
    <input id="file" @change="handleFileChange" accept="image/*" type="file" :multiple="false">
  </div>
</template>
<script>
import uploadAvatar from '@/utils/uploadAvatar'
export default {
  methods: {
    async handleFileChange(e) {
      let file = e.target.files[0];
      //调用封装的uploadAvatar.js
     const res = await uploadAvatar(file);
    }
  }
};
</script>
<style lang="less" scoped>
</style>

2、处理文件流,传给后台(uploadAvatar.js)

import axios from "axios";
async function uploadAvatar (file) {
  let result = {};
  //用FormData传输
  let param = new FormData();
  param.append("fileImage", file);
 //判断图片大小和格式
  if (file.size >= 10 * 1024 * 1024) {
    result = { picture: "sobig", msg: "图片超过了10M", url: "" };
  } else if (!(['image/jpeg','image/jpg','image/png'].includes(file.type))) {
    result = { picture: "error", msg: " 只支持 jpg/png/jpeg 格式图片", url: "" };
  } else {
  //设置请求头
    let config = {
      headers: { "Content-Type": "multipart/form-data" }
    };
    const { data } = await axios.post(
      "请求接口",
      param,
      config
    );
    if (data.status != "200") {
      result = { picture: "error", msg: "图片上传失败,请重试", url: "" };
    } else {
      result = { picture: "over", msg: "上传成功", url: data.url };
    }
  }
  return result;
}
export default uploadAvatar;

总结

工作中的小总结,有问题欢迎提出。

Logo

前往低代码交流专区

更多推荐