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

前端页面:

    <el-dialog title="添加图文" :visible.sync="dialogVisible">
      <el-form :model="configForm" ref="configForm" label-width="100px"
               :rules="rules"
               v-loading="loading2">
        <h3 class="title modal-headline">添加图文</h3>
        <el-form-item label=" 图文标题" prop="imgTitle">
          <el-input v-model="configForm.imgTitle"
                    type="text"
                    auto-complete="off" placeholder="请输入标题"></el-input>
        </el-form-item>
        <el-form-item label="添加文字" prop="imgText">
          <el-input v-model="configForm.imgText"
                    type="textarea"
                    auto-complete="off" placeholder="请输入文字内容"></el-input>
        </el-form-item>
        <el-form-item label="添加图片" ref="uploadElement" prop="img">
          <el-input v-model="configForm.img" v-if="false"></el-input>
          <el-upload
            class="upload-demo"
            :on-success="handleAvatarSuccess"//这里是后台的回调信息
            accept="image/jpeg,image/jpg,image/png"//控制类型
            :action="materialPictureAndText()"//后台方法
            :auto-upload="false"//关闭自动上传
            :before-upload="beforeUpload2"//文件控制
            ref="upload"
            :on-change="handleChange"//文件状态改变时的钩子,添加文件、上传成功和上传失败时都会被调用
            multiple
            :data="configForm"> //表单数据
            <el-button type="success" size="small">选择文件</el-button>
          </el-upload>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary"
                   @click="submitImg('configForm')" >确 定</el-button>
        <el-button @click="dialogVisible = false">取 消</el-button>
      </div>
    </el-dialog>

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<String, Object> materialPictureAndText(HttpServletRequest request,
                                                      @RequestParam(value = "imgTitle", required = false) String imgTitle,
                                                      @RequestParam(value = "file", required = false) MultipartFile file) {

        if (file.isEmpty()) {
            HashMap<String, Object> 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服务器,应该用其他也一样的,在代码里配置映射路径

先在配置文件中:

在写一个配置文件配置映射路径,然后在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后端框架,Vue前端框架以及Element UI组件库进行实现。 首先,在Vue前端页面中,可以使用Element UI中的Upload组件实现文件上传功能。可以在页面中定义一个Upload组件,设置action属性为上传接口的URL,设置headers属性为请求头部信息,设置on-success属性为上传成功后的回调函数。具体代码如下: ``` <template> <div> <el-upload class="avatar-uploader" action="/api/uploadAvatar" :headers="{ Authorization: 'Bearer ' + token }" :show-file-list="false" :on-success="handleSuccess"> <img v-if="imageUrl" :src="imageUrl" class="avatar"> <i v-else class="el-icon-plus avatar-uploader-icon"></i> </el-upload> </div> </template> <script> import { getToken } from '@/utils/auth' export default { data() { return { imageUrl: '', token: getToken() } }, methods: { handleSuccess(response) { this.imageUrl = response.data.url } } } </script> ``` 其中,token是用于认证的令牌,可以通过getToken函数获取。handleSuccess函数是上传成功后的回调函数,其中response.data.url表示上传成功后的图片URL。 然后,在Spring Boot后端接口中,可以使用Spring MVC的注解@RequestParam来接收上传的文件。具体代码如下: ``` @RestController @RequestMapping("/api") public class UploadController { @PostMapping("/uploadAvatar") public JsonResult uploadAvatar(@RequestParam("file") MultipartFile file) throws IOException { // 处理上传的文件 return JsonResult.ok("url", "http://www.example.com/avatar.jpg"); } } ``` 其中,@PostMapping注解表示接收POST请求,@RequestParam("file")注解表示接收名为file的文件参数。处理上传的文件后,可以返回一个JsonResult对象,其中包含上传成功后的图片URL。
评论 19
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值