springboot+vue+element-ui实现图文上传(表单文字和图片一起入库)

前端页面:

    
      
        
        
          
        
        
          
        
        
          
           //表单数据
            选择文件
          
        
      
      
    

js:

      submitImg (forName) {
        let self = this
        this.$confirm('此操作将无法撤回, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          self.$refs[forName].validate((valid) => {
            if (valid) {
              self.$refs.upload.submit()
              self.dialogVisible = false
              self.loading2 = false
            } else {
              return false
            }
          })
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消更新'
          })
        })
      },

      handleAvatarSuccess (response, file) {
        let self = this
        let resp = response
        console.log(response)
        if (resp.result === 200) {
          setTimeout(() => {
            self.dialogVisible = false//关闭弹窗
     
            self.$refs.upload.clearFiles()
            self.$message.success(resp.msg)//显示后台信息
            self.getImgData()//上传后刷新表单
          }, 1000)
        } else {
          self.$message.error(resp.msg)//显示后台信息
          self.$refs.upload.clearFiles()//清空表单
        }
      },
      materialPictureAndText () {
        return Config.context + '/pictureManage/materialPicture' //前面是为了方便线上加的
      },
      beforeUpload2 (file) {
        const isLt2M = file.size < 1024 * 1024 * 2
        // console.log('大小' + isLt2M)
        if (!isLt2M) {
          this.$message.error('上传文件大小不能超过 2MB!')
        }
        let size = file.size / 1024
        console.log('大小' + size)
        let _URL = window.URL || window.webkitURL
        let img = new Image()
        img.onload = function () {
          let width = img.width
          let height = img.height
          console.log('width--->' + width)
          console.log('height--->' + height)
        }
        img.src = _URL.createObjectURL(file)
        return isLt2M
      },

后台控制层:

    @PostMapping(value = "materialPicture", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public Map materialPictureAndText(HttpServletRequest request,
                                                      @RequestParam(value = "imgTitle", required = false) String imgTitle,
                                                      @RequestParam(value = "file", required = false) MultipartFile file) {

        if (file.isEmpty()) {
            HashMap resultMap = new HashMap<>();
            resultMap.put("msg", "请上传图片");
            return resultMap;
        } else {
            String fileName = file.getOriginalFilename();  // 文件名
            String suffixName = fileName.substring(fileName.lastIndexOf("."));
            String filePath = path;//这个path就是你要存在服务器上的
            fileName = UUID.randomUUID() + suffixName; // 新文件名
            File dest = new File(filePath + fileName);
            if (!dest.getParentFile().exists()) {
                dest.getParentFile().mkdirs();
            }
            try {
                file.transferTo(dest);
            } catch (IOException e) {
                e.printStackTrace();
            }
            Picture materialPicture = new Picture();
            materialPicture.setImgTitle(imgTitle);
            String filename = apiUrl + fileName;
            materialPicture.setPicture_url(filename);
            return pictureService.imgUpload(materialPicture);//这里就是上传图片返回的信息,成功失败异常等,前端根据字段接收就是了
        }
    }

关于图片的显示,我是用了tomcat服务器,应该用其他也一样的,在代码里配置映射路径

先在配置文件中:

springboot+vue+element-ui实现图文上传(表单文字和图片一起入库)_第1张图片

在写一个配置文件配置映射路径,然后在tomcat下面跑即可:

@Configuration
public class MyWebAppConfigurer implements WebMvcConfigurer {

    @Value("${file.staticAccessPath}")
    private String staticAccessPath;
    @Value("${file.uploadFolder}")
    private String uploadFolder;

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler(staticAccessPath).addResourceLocations("file:" + uploadFolder);
        WebMvcConfigurer.super.addResourceHandlers(registry);
    }
}

 

你可能感兴趣的:(spring,boot学习笔记,Java,前端)