antd vue上传图片至后端

最近项目有个需求需要在前端vue上传图片,然后在后端将图片存到本地的一个文件夹下。

1、vue

这里是将上传图片封装成了一个组件来使用,组件名为 upload-image.vue

<template>
  <div class="clearfix">
    <!--
        name    —— 向后端传递数据时会要用到
        action  —— 后端路径
    -->
    <a-upload
        name="faceImage"            
        :headers="headers"
        :action="fileurl"
        list-type="picture-card"
        v-model:file-list="fileList"
        :before-upload="beforeUpload"
        @preview="handlePreview"
        @change="handleChange"
    >
      <div v-if="fileList.length < imgNum">
        <a-icon type="plus" />
        <div class="ant-upload-text">
          上传图片
        </div>
      </div>
    </a-upload>
    <a-modal :visible="previewVisible" :footer="null" @cancel="handleCancel">
      <img alt="example" style="width: 100%" :src="previewImage" />
    </a-modal>
  </div>
</template>

<script>
import mitt from "@/utils/mitt";

function getBase64(file) {
  return new Promise((resolve, reject) => {
    const reader = new FileReader();
    reader.readAsDataURL(file);
    reader.onload = () => resolve(reader.result);
    reader.onerror = error => reject(error);
  });
}

export default {
  name: "uoload-image",
  data(){
    return{
      imgNum:1,              //设置最多可以上传的图片数量
      headers: {    
        'token': localStorage.getItem('token'),
      },
      fileurl:"/api/file/upload",       //上传到后端的路径
      previewVisible: false,
      previewImage: '',
      fileList: []
    }
  },
  methods:{
    handleCancel() {
      this.previewVisible = false;
    },
    async handlePreview(file) {
      if (!file.url && !file.preview) {
        file.preview = await getBase64(file.originFileObj);
      }
      this.previewImage = file.url || file.preview;
      this.previewVisible = true;
    },
    // 检查图片格式和图片大小
    beforeUpload(file){
      //图片格式限制为 jpeg、png
      const isJpgOrPng = file.type === 'image/jpeg' || file.type === "image/png";
      if (!isJpgOrPng){
        this.$message.error("请选择jpg/png图片");
      }
       
      //图片大小限制为 2M以内
      const isLt2M = file.size/1024/1024 <= 2;
      if (!isLt2M){
        this.$message.error("图片大小不能超过2MB,请重新上传");
      }
      return isJpgOrPng && isLt2M;
    },
    handleChange ({ file, fileList }) {
      this.fileList = fileList;
      if (file.hasOwnProperty('error')){
        this.$message.error("图片上传失败");
        return;
      }
    },
  }
}
</script>

<style scoped>
.ant-upload-select-picture-card i {
  font-size: 32px;
  color: #999;
}

.ant-upload-select-picture-card .ant-upload-text {
  margin-top: 8px;
  color: #666;
}
</style>

注意:后端路径有个地方需要注意,关于这里的 ' /api ',我在vue.config.js做了跨域处理

2、后端springboot

@RestController
@RequestMapping("/file")
public class UploadImageController {
    //这里的 faceImage 就是 a-upload 的 name 属性
    @PostMapping("/upload")
    public void uploadImage(@RequestParam("faceImage") MultipartFile pic) {
        /*
         * 编码为字符串
         */
        String base64Str = "";
        try {
            base64Str = Base64Utils.encodeToString(pic.getBytes());     //将图片转化为base64格式
            String imgName = pic.pic.getOriginalFilename();             //获取到图片原本的名字
            storeImageAtLocal(base64Str, imgName);                      //为了方便在其他地方调用,这里封装成了一个工具类
        }catch (IOException e){
            e.printStackTrace();
        }
    }
}
public class UploadUtil {
    //这里的pathName表示 你要存到哪,图片名叫啥,如D:\\resources\\image\\smile.jpg

    public static void storeImageAtLocal(String base64ImgData,String pathName){
        Base64.Decoder decoder = Base64.getDecoder();
        byte[] bytes = decoder.decode(base64ImgData);
        /*
         * 字节流转文件
         */
        FileOutputStream fos = null;
        try {
            fos = new FileOutputStream(pathName);
            fos.write(bytes);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (fos != null){
                try {
                    fos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    //本地图片转base64编码数据
    public static String getImageBase64Data(String localPath){
        File file = new File(localPath);    //URL url = new URL(src);
        byte[] data = null;
        try {
            InputStream in = new FileInputStream(file);  //InputStream in = url.openStream();
            data = new byte[in.available()];
            in.read(data);
            in.close();
        } catch (IOException e) {
            e.printStackTrace();
        }

        Base64.Encoder encoder = Base64.getEncoder();
        return encoder.encodeToString(data);
    }

}
  • 4
    点赞
  • 23
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
首先,你需要在前端创建一个上传文件的表单,可以使用 antd 的 `Upload` 组件,代码如下: ```vue <template> <div> <a-upload :action="uploadUrl" :before-upload="beforeUpload" :on-success="handleUploadSuccess" > <a-button> <a-icon type="upload" /> 点击上传 </a-button> </a-upload> </div> </template> <script> export default { data() { return { uploadUrl: 'http://your-backend-api.com/upload', // 上传文件的接口地址 } }, methods: { beforeUpload(file) { // 在上传前进行一些校验,比如文件大小、文件类型等,返回 false 可以阻止上传 }, handleUploadSuccess(response) { // 上传成功后的回调函数,response 是后端返回的数据 }, }, } </script> ``` 然后,在后端编写一个文件上传的接口,可以使用 Express 框架和 multer 中间件来处理文件上传,代码如下: ```javascript const express = require('express') const multer = require('multer') const app = express() // 设置文件上传的存储路径和文件名 const storage = multer.diskStorage({ destination(req, file, cb) { cb(null, 'uploads/') // 存储路径 }, filename(req, file, cb) { cb(null, `${Date.now()}-${file.originalname}`) // 文件名 }, }) // 创建 multer 中间件 const upload = multer({ storage }) // 定义文件上传的路由 app.post('/upload', upload.single('file'), (req, res) => { // req.file 是上传的文件对象,可以通过 req.file.path 获取文件在服务器上的路径 // 在这里可以对上传的文件进行一些处理,比如保存到数据库或者返回文件的下载链接等 }) // 启动服务器 app.listen(3000, () => { console.log('Server started on port 3000') }) ``` 注意,上面的代码中 `upload.single('file')` 中的 `'file'` 是前端表单中的文件字段名,要与前端代码中的 `before-upload` 属性对应。另外,需要在服务器端设置静态文件目录,以便在浏览器中访问上传的文件,可以使用 Express 的 `express.static` 中间件来实现: ```javascript app.use(express.static('uploads')) ``` 这样,当你上传一个文件后,它就会被保存在 `uploads` 目录下,并且可以在浏览器中通过 `http://your-backend-api.com/uploads/文件名` 的方式访问。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值