目录

前端多文件传送后端

目录

前端多文件传送后端

使用技术:

vue2+springboot

注:后端基于若依框架,使用的是其工具类上传,但是已经能接受前端传来的文件,注释内容无需理会

参考视频如下

前端:

<template xmlns="http://www.w3.org/1999/html">
  <div>
    <input  type="file" name="file" @change="fileChange">

    <button type="submit" @click="upload">提交</button>
    <span v-for="a in fileList"><br>{{a.name}}</span>

</div>
</template>

<script>
import {myTestUpload1} from "@/api/system/filesc";

export default{
name: "Index",
data(){
return{
ImgUrl: "",
filObject: "",
fileList: [],

      }
    },
    methods: {
      fileChange(e){
        //获取上传的file对象
       // let file=e.target.files[0];
       //  this.filObject = file;
       //  if(file.size>2*1024*1024){
       //    alert("文件不能大于2MB");
       //  }
       //  if(file.type!="application/pdf"){
       //    alert("文件格式必须是pdf");
       //  }
       //  //将file对象转换为blob对象并且截取前5000字节
       //  let _blob=new Blob([file]).slice(0, 5000);
       //  //将blob对象转换为file对象
       //  let _file=new File([_blob],"test.png");
       //
       //  let fr = new FileReader();
       //  //将file对象读取为base64,为异步转换需要onload监听
       //  fr.readAsDataURL(file);
       //  let that = this;
       //  fr.οnlοad=function (){
       //    //result为转换结果
       //    that.ImgUrl=fr.result;
       //  }
       //  console.log(_blob)
       //  console.log(_file)
        this.fileList.push(e.target.files[0])
        console.log(this.fileList)
      },
      upload(){
        let formData = new FormData();
        //formData拼接file
        this.fileList.forEach((item)=>{
          formData.append("testFile",item);
        })


        let that = this;
        myTestUpload1(formData).then(response=>{
          that.fileList = "";
        })
      }

    }

}

</script>

请求:

// 图片上传
export function myTestUpload1(data) {
return request({
url: '/system/filesc/scFile/',
method: 'post',
data: data
})
}

后端:

@PostMapping("/scFile")
public void myTestUpload(@RequestPart MultipartFile testFile[]) throws IOException {
System.out.println(testFile.length);
for (MultipartFile m:testFile) {
if (!m.isEmpty()){
String uploadFileName = FileUploadUtils.upload(m);
System.out.println(uploadFileName);
}

        }
    }