万普插件库

jQuery插件大全与特效教程

SpringBoot示例,第1期:文件上传(前端)

1个参数+自动提交

写法1:

upload(@RequestParam("myfile1") MultipartFile myfile, @RequestParam("type") String type)

写法2:

upload(@RequestParam("myfile1") MultipartFile myfile, String type)

前台写法:

const data = new FormData()
data.append('myfile1', item.file)
data.append('type', "3")
this.$axios.post('http://localhost:8080/upload',data).then

完整代码:

<template>
  <div class="search-result" style="display: flex;justify-content: flex-start">
    <el-upload
      type="warning"
      v-loading="uploading"
      action
      :accept="realAccept"
      :before-upload="handleBeforeUpload"
      :http-request="uploadFile"
      :show-file-list="false"
      class="batch-import">
      <el-button plain class="btn-style">自动上传</el-button>
    </el-upload>
  </div>
</template>
<style scoped lang="scss">
</style>
<script>
export default {
  name: "testDownload",
  data() {
    return {
      realAccept: '.jpg,.png,.pdf,.PDF,.doc,.docx,.xls,.xlsx,.txt',
      uploading: false,
    }
  },
  methods: {
    handleBeforeUpload(file) {
      if (JSON.stringify(this.param) === '{}') {
        this.$message({
          message: '参数param不能为空',
          type: 'warning'
        })
        return false
      }
      const suffix = file.name.substring(file.name.lastIndexOf('.'))
      if (this.realAccept.indexOf(suffix) === -1) {
        this.$message({
          message: '上传文件只能是' + this.realAccept + '格式!',
          type: 'warning'
        })
        return false
      } else {
        return true
      }
    },
    uploadFile(item){
      const data = new FormData()
      data.append('myfile1', item.file)
      data.append('type', "3")
      this.$axios.post('http://localhost:8080/upload',data).then((res) => {
        if(res.data.code == 500){
          alert("导入失败:"+res.data.msg);
          this.uploading = false;
          return;
        }else{
          alert('导入成功');
        }
        this.handleQuery();
        this.uploading = false;
      }).catch(error =>{
        console.log("----",error)
        this.uploading = false;
      }).finally(() => {
        this.uploading = false;
      })
    },
  }
}
</script>

N个form参数

1个参数很容易,如果一堆参数呢?

后台:

public String upload(@RequestParam("myfile") MultipartFile file, Users users)

这种是form参数:

uploadFile(item){
const data = new FormData()
data.append('myfile1', item.file)
data.append('userId', "3")
data.append('userName', "3666")
this.$axios.post('http://localhost:8080/upload',data).then((res) => {})

缺点,如果参数100个呢,一个个append明显不现实。

N个JSON参数

这种是一个json的参数,其实用的比较少,因为大部分不会有太多参数的。

@PostMapping("upload")
public String upload(@RequestParam("myfile") MultipartFile file,@RequestPart("users") Users users)

前台:注意使用Blob,然后指定json类型

uploadFile(item){
const data = new FormData()
data.append('myfile1', item.file)
data.append('u', new Blob([JSON.stringify({userId:"3666",userName:"aaa"})],{type:'application/json'}))
this.$axios.post('http://localhost:8080/upload',data).then((res) => {})

手动提交

前面全部是自动提交,也就是选择文件后就马上提交了,不用点确认什么的。

后台:

String upload1(@RequestParam("file") MultipartFile file)

前台:

<template>
  <div class="search-result" style="display: flex;justify-content: flex-start">
    <el-upload
      class="upload-demo"
      ref="upload"
      action="http://localhost:8080/upload1"
      :before-upload="handleBeforeUpload"
      :file-list="fileList"
      :auto-upload="false">
      <el-button slot="trigger" size="small" type="primary">选取文件</el-button>
      <el-button style="margin-left: 10px;" size="small" type="success" @click="submitUpload">手动上传</el-button>
      <div slot="tip" class="el-upload__tip">只能上传jpg/png文件,且不超过500kb</div>
    </el-upload>
  </div>
</template>
<style scoped lang="scss">
</style>
<script>
export default {
  name: "testDownload",
  data() {
    return {
      realAccept: '.jpg,.png,.pdf,.PDF,.doc,.docx,.xls,.xlsx,.txt',
      uploading: false,
      fileList:[]
    }
  },
  methods: {
    handleBeforeUpload(file) {
      this.fileList.push(file);
      if (JSON.stringify(this.param) === '{}') {
        this.$message({
          message: '参数param不能为空',
          type: 'warning'
        })
        return false
      }
      const suffix = file.name.substring(file.name.lastIndexOf('.'))
      if (this.realAccept.indexOf(suffix) === -1) {
        this.$message({
          message: '上传文件只能是' + this.realAccept + '格式!',
          type: 'warning'
        })
        return false
      } else {
        return true
      }
    },
    submitUpload() {
      this.$refs.upload.submit();
    },
  }
}
</script>

前台太灵活了,反而各种方式眼花缭乱,没有一个固定的写法。

这种方式后台@RequestParam中的名称只能和变量名一致。

如果不一致的话就不行了。

<template>
  <div class="search-result" style="display: flex;justify-content: flex-start">
    <el-upload
      class="upload-demo"
      ref="upload"
      :http-request="uploadFile"
      :file-list="fileList"
      :on-success="handleSuccess"
      :on-error="handleError"
      :auto-upload="false">
      <el-button slot="trigger" size="small" type="primary">选取文件</el-button>
      <el-button style="margin-left: 10px;" size="small" type="success" @click="submitUpload">手动上传</el-button>
      <div slot="tip" class="el-upload__tip">只能上传jpg/png文件,且不超过500kb</div>
    </el-upload>
  </div>
</template>
<script>
import axios from 'axios';
export default {
  data() {
    return {
      fileList: []
    };
  },
  methods: {
    beforeUpload(file) {
      // 文件上传前的检查逻辑,例如文件大小和类型验证
      const isJPG = file.type === 'image/jpeg' || file.type === 'image/png';
      const isLt2M = file.size / 1024 / 1024 < 2;
      if (!isJPG) {
        this.$message.error('上传图片只能是 JPG/PNG 格式!');
      }
      if (!isLt2M) {
        this.$message.error('上传图片大小不能超过 2MB!');
      }
      return isJPG && isLt2M;
    },
    uploadFile(item){
      const data = new FormData()
      data.append('myfile1', item.file)
      data.append('u', new Blob([JSON.stringify({userId:"3666",userName:"aaa"})],{type:'application/json'}))
      this.$axios.post('http://localhost:8080/upload',data,{
        headers: {
          'Content-Type': 'multipart/form-data'
        },
      }).then((res) => {
        if(res.data.code == 500){
          alert("导入失败:"+res.data.msg);
          this.uploading = false;
          return;
        }else{
          alert('导入成功');
        }
        this.handleQuery();
        this.uploading = false;
      }).catch(error =>{
        console.log("----",error)
        this.uploading = false;
      }).finally(() => {
        this.uploading = false;
      })
    },
    handleSuccess(response, file, fileList) {
      this.$message.success('上传成功');
    },
    handleError(error, file, fileList) {
      this.$message.error('上传失败');
    },
    submitUpload() {
      this.$refs.upload.submit();
    },
  }
};
</script>
控制面板
您好,欢迎到访网站!
  查看权限
网站分类
最新留言