SpringBoot结合Vue实现图片上传

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 "图片上传失败!";
    }