SpringBoot结合Vue实现图片上传

12 篇文章 0 订阅

SpringBoot结合Vue实现图片上传

效果

  • 页面图片上传
  • 上传完成之后

Vue中图片上传核心代码

  • 在main.js中引入axios

     

    import axios from 'axios'
    Vue.prototype.$ajax = axios;
    
  • 在图片上传的文件中写文件上传控件

     

    <li>
        <h3>添加新图:</h3>
        <input type="file" id="saveImage" name="myphoto" accept="image/png,image/gif,image/jpeg"
               ref="new_image">
        <el-button @click="addImage">确认添加</el-button>
    </li>
    
  • 添加图片函数

     

    addImage: function () {
        let self = this;
        if (self.$refs.new_image.files.length !== 0) {
            var formData = new FormData()
            formData.append('image_data', self.$refs.new_image.files[0]);
            //单个文件进行上传
            self.$ajax.post('/addImage', formData, {
                headers: {
                    "Content-Type": "multipart/form-data"
                }
            }).then(response => {
    
            })
        }
    }
    

SpringBoot中图片下载核心控制类代码

  • 方法核心代码

     

    @RequestMapping("/addImage")
    @ResponseBody
    public String addImage(@RequestParam(name = "image_data", required = false) MultipartFile file) {
        //文件上传
        if (!file.isEmpty()) {
            try {
                //图片命名
                String newCompanyImageName = "newPIC";
                String newCompanyImagepath = "D:\\"+newCompanyImageName;
                File newFile = new File(newCompanyImagepath);
                if (!newFile.exists()) {
                    newFile.createNewFile();
                }
                BufferedOutputStream out = new BufferedOutputStream(
                        new FileOutputStream(newFile));
                out.write(file.getBytes());
                out.flush();
                out.close();
            } catch (FileNotFoundException e) {
                e.printStackTrace();
                return "图片上传失败!";
            } catch (IOException e) {
                e.printStackTrace();
                return "图片上传失败!";
            }
        }
        return "图片上传失败!";
    }
  • 5
    点赞
  • 30
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 5
    评论
评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

乘风御浪云帆之上

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值