当前位置:   article > 正文

el-upload上传图片给SpringBoot后端

el-upload上传图片给SpringBoot后端
  • 需求
    我的需求是,将上传文件的el-upload放到一个el-form里面,点击保存才提交,所以不能直接用action的方式,下面采用自定义上传的方式来完成
  • Vue前端
    主要是使用editForm.imgList来保存图片的信息,注意这里是一个对象,其格式如下

我这里后端传回来的是一个字符串数组,把他转为对象如下

 this.editForm.imgList = row.imgList.map((url,index) => ({
          name:index,
          url: url,
        }));
  • 1
  • 2
  • 3
  • 4

前端主要代码

<el-form>
        <el-form-item label="描述" prop="description">
          <el-input type="textarea" :rows="6" v-model="editForm.description" auto-complete="off"
                    placeholder="请输入描述"></el-input>
        </el-form-item>
        
        <el-form-item label="图片" prop="description">
          <el-upload
            action=""
            list-type="picture-card"
            multiple
            :on-change="handlChange"
            :file-list="editForm.imgList"
            :on-error="handleErr"
            ref="upload"
            :auto-upload="false">
            <i slot="default" class="el-icon-plus"></i>
            <div slot="file" slot-scope="{file}">
              <img
                class="el-upload-list__item-thumbnail"
                :src="file.url" alt=""
              >
              <span class="el-upload-list__item-actions">
                <span
                  class="el-upload-list__item-preview"
                  @click="handlePictureCardPreview(file)"
                >
                  <i class="el-icon-zoom-in"></i>
                </span>

                <span

                  class="el-upload-list__item-delete"
                  @click="handleRemove(file)"
                >
                  <i class="el-icon-delete"></i>
                </span>
              </span>
            </div>
          </el-upload>


        </el-form-item>
      </el-form>
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • js主要代码
 data() {
 
    return {
   
      editForm: {
        imgList: [],
     
    },
 }
methods: {
    handleRemove(file) {

      let arr = this.$refs.upload.uploadFiles
      // 2.从pics数组中,找到图片对应的索引值
      let index = arr.indexOf(file)
      // 3.调用splice方法,移除图片信息
      arr.splice(index, 1)

    },
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url;
      this.dialogVisible = true;
    },
    handlChange(file, fileList) {
      this.editForm.imgList = fileList;
      console.log("change",this.editForm.imgList)
    },
      
    submitForm() {

      let formData = new FormData(); //  用FormData存放上传文件
      //将图片转为FormData格式
//formData.append() 方法向 FormData 对象添加同一个键(key)的多个值时,
//实际上是在创建一个值的列表,而这个键会与每个添加的值关联起来,
//后端接收到的就是一个List
      this.editForm.imgList.forEach(file => {
        console.log(file.raw)
        console.log(file.size)
        formData.append('files', file.raw)
      })
      console.log(formData)
      //自定义上传
      axios({
        method: "post",
        url: "http://localhost:8089/upload",
        headers: {
          'Content-Type': 'multipart/form-data',
          token: localStorage.getItem('logintoken')
        },
        data:formData
        // traditional: true,
      }).then(function (res){
        // console.log(res)
        return res;
      });//相当于function(res){ret   
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • SpringBoot后端代码

@RestController
@CrossOrigin
public class ManageController {
    @Value("${saveimg.location.attractions}")
    String attractionLocation;
    
 	@RequestMapping(value = "upload")
    public void uploadImg(@RequestParam("files") List<MultipartFile> files){
        System.out.println("files = " + files);
		for (MultipartFile file : files) {
            if (!file.isEmpty()) {
                try {
                    // 构建真实的文件路径
                    Path path = Paths.get(attractionLocation + file.getOriginalFilename());
                    // 确保目录路径存在
                    Files.createDirectories(path.getParent());

                    // 将上传文件保存到指定位置
                    file.transferTo(path);

                    // 或者使用这种方式
                    // byte[] bytes = file.getBytes();
                    // Files.write(path, bytes);
                    System.out.println("保存成功");
                } catch (IOException e) {
                    e.printStackTrace();
                    System.out.println( "上传失败");
                }
            }
            else {
                System.out.println("失败");
            }
        }
   }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/羊村懒王/article/detail/384064
推荐阅读
相关标签
  

闽ICP备14008679号