在线教育项目1--使用element-ui配合springboot oss上传文件/视频到阿里云oss

1前端代码:

<template>
  <div class="newWorkForm">
    <!--新增通知对话框-->
    <el-dialog
        title="新增作业"
        :before-close="handleClose"
        :visible.sync="dialogVisible"
        width="50%"
        v-loading="loading"
        element-loading-text="拼命上传中"
        element-loading-spinner="el-icon-loading"
        element-loading-background="rgba(0, 0, 0, 0.8)"
    >
      <el-form
        :model="Form"
        :rules="rules"
        ref="Form"
        label-width="100px"
        class="demo-ruleForm"
      >
      <!--文件基础内容-->
        <el-form-item label="发布者姓名" prop="uname">
          <el-input v-model="Form.uname"></el-input>
        </el-form-item>
        <el-form-item label="文件备注" prop="name">
          <el-input v-model="Form.name"></el-input>
        </el-form-item>
        <el-form-item label="文件类型" prop="type">
         <el-select v-model="Form.type" placeholder="请选择类型">
             <el-option label="图片" value="image"></el-option>
              <el-option label="视频" value="media"></el-option>
          </el-select>
        </el-form-item>


        <!--文件内容上传区-->
        <el-form-item label="选择文件" required>
             <el-upload
                class="upload-demo"
                action="https://jsonplaceholder.typicode.com/posts/"
                :auto-upload="false"
                :http-request="uploadFile"
                ref="upload"
                :multiple="false"
                 list-type="picture"
          >
            <el-button size="small" type="primary">点击上传</el-button>
          </el-upload>
        </el-form-item>
      </el-form>


      <span slot="footer" class="dialog-footer">
         <el-button type="primary" @click="submitForm('Form')"
            >立即发布</el-button
          >
          <el-button @click="resetForm('Form')">重置</el-button>
        </el-form-item>
      </span>
    </el-dialog>
  </div>
</template>
<script>
export default {
  data() {
    return {
        imgsArr:[],
        loading:false,
        Form: {
            uname:"",
            name:"",
            type:"",
        },
      rules: {
        uname: [
          { required: true, message: "请输入姓名", trigger: "blur" },
          { min: 1, max: 20, message: "长度在 1 到 20 个字符", trigger: "blur" },
        ],
        name: [
          { required: true, message: "请输入通知内容", trigger: "blur" },
          { min: 1, max: 20, message: "长度在 1 到 20 个字符", trigger: "blur" },
        ],
        type: [
          { required: true, message: "请选择类型", trigger: "blur" },
          { min: 1, max: 20, message: "长度在 1 到 20 个字符", trigger: "blur" },
        ]
      },
    };
  },
  props: {
    dialogVisible: {
      type: Boolean,
    },
  },
  inject:["reload"],
  methods: {
    uploadFile(file){
           this.imgsArr.push(file.file);//往一个数组中添加图片数据
      },
    handleClose() {
      this.$emit("cancle");
    },
    cancle() {
      this.$emit("cancle");
    },
    confirm() {
      this.$emit("confirm");
    },
    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
           if(this.imgsArr.length>1){
            this.$message.error("请不要上传超过一个文件");
            return;
          }
          this.loading=true;
           var formdata=new FormData();
           this.$refs.upload.submit();
            if(this.imgsArr.length>0){
                this.imgsArr.forEach((img,index)=>{
                 formdata.append(`file`,img);//这里用到index++,防止前面添加的图片被后面的覆盖,下面后端代码有讲如何循环这个数组
              })
            }else{
                this.$message.error("请同时附上相应文件");
                return;
            }
          formdata.append("uname",this.Form.uname);
          formdata.append("name",this.Form.name);
          formdata.append("type",this.Form.type);
          formdata.append("courseId",1);
          let config = {
                headers: {
                'Content-Type': 'multipart/form-data'
                }
            }//设置请求头!
            console.log(formdata.getAll("file"));
          this.$http.post("/file/addFile",formdata,config).then(res=>{
              if(res.data.status==0){
                this.loading=false;
                this.$message.success("发布成功");
                this.reload();
              }else{
                this.$message.error("系统异常,发布失败!");
                 this.$emit("cancle");
              }
          })
        } else {
          this.$message.error("参数不正确!");
          return false;
        }
      });
    },
    resetForm(formName) {
      this.$refs[formName].resetFields();
    },
  },
};
</script>
<style lang="less" scoped>
   .newWorkForm{
       /deep/.el-input__inner{
           width: 80%;
       }
   }
</style>

预览:
在这里插入图片描述

二后端java代码:

怎么开启oss服务?百度一下


@RestController
@RequestMapping(value = "/file")
public class fileController {
    public static String ENDPOINT = "..你的endpoint";
    public static String ACCESSKEYID = ".....";
    public static String ACCESSKEYSECRET = "......";
    public static String BUCKETNAME = "....";
    @Autowired
    fileServer fileServer;

    public ListeningExecutorService executorService= MoreExecutors.listeningDecorator(Executors.newCachedThreadPool());

    @PostMapping(value = "/addFile")
    public ServerResponse addFile(@RequestParam("file") MultipartFile file,@RequestParam("uname")String uname,
                                 @RequestParam("name")String name,@RequestParam("type")String type,@RequestParam("courseId")int courseId) throws Exception {
        InputStream stream=file.getInputStream();
        String filename=System.currentTimeMillis()+file.getOriginalFilename();
        OSSClient client=new OSSClient(ENDPOINT,ACCESSKEYID,ACCESSKEYSECRET);
        PutObjectResult result=client.putObject(BUCKETNAME,type+"/"+filename,stream);
        client.shutdown();
        String url= type+"/"+filename;//这里直接用字符串拼接就能访问oss,但是要先设置公共读
        return fileServer.addFile(courseId,uname,url,name, type);
    }


    //获取文件列表
    @GetMapping(value = "/getFileList/{courseId}")
    public ServerResponse getFileList(@PathVariable("courseId") int courseId){
        return fileServer.getFileList(courseId);
    }
}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值