Vue与SpringBoot(六)实现多图片上传及分页显示

效果图如下:

代码如下:

1、图片上传页面代码如下:

<template>
    <el-upload
    class="img-upload"
    ref="upload"
    action="http://localhost:9009/api/multiPicUpload"
    :on-preview="handlePreview"
    :before-remove="handleRemove"
    :on-success="handleSuccess"
    multiple
    :limit="3"
    :on-exceed="handleExceed"
    :file-list="fileList">
    <el-button size="small" type="primary">点击上传</el-button>
    <div slot="tip" class="el-upload_tip">只能上传jpg/png文件,且不超过500kb,一次最多可以选择3个文件</div>
    </el-upload>
</template>

<script>
export default {
  name: 'MultiImgUpload',
  data () {
    return {
      fileList: [],
      url: ''
    }
  },
  methods: {
    handleRemove (file, fileList) {
      console.log(file, fileList)
    },
    handlePreview (file) {
      console.log(file)
    },
    handleExceed (files, fileList) {
      this.$message.warning(`当前限制选择 3 个文件,本次选择了 ${files.length} 个文件,共选择了 ${files.length + fileList.length} 个文件`)
    },
    beforeRemove (file, fileList) {
      return this.$confirm(`确定移除${file.name}?`)
    },
    handleSuccess (response) {
      this.url = response
      this.$emit('onUpload')
      this.$message.warning('上传成功')
    },
    clear () {
      this.$refs.upload.clearFiles()
    }
  }
}
</script>

<style scoped>
  .img-upload {
    /*height: 200px;*/
  }
</style>

 

2、图片列表页面,import上传页面

<template>
  <div>
    <el-row style="margin-bottom:15px;">
       {{picName}}
       <multi-img-upload @onUpload="uploadImg" ref="mulitiImgUpload"></multi-img-upload>
    </el-row>
    <el-row style="height: 650px;">
      <el-tooltip effect="dark" placement="right"
                  v-for="item in pics.slice((currentPage-1)*pagesize,currentPage*pagesize)"
                  :key="item.id">
        <p slot="content" style="font-size: 14px;margin-bottom: 6px;">{{item.picName}}</p>
        <el-card style="width: 185px;margin-bottom: 15px;height: 199px;float: left;margin-right: 15px" class="book"
                 bodyStyle="padding:10px" shadow="hover">
         <div class="cover">
            <img :src="item.picPath">
          </div>
          <div class="info">
            <i class="el-icon-delete" @click="deletePicInfo(item.id)"></i>
          </div>
        </el-card>
      </el-tooltip>      
    </el-row>
    <el-row>
      <el-pagination
        @current-change="handleCurrentChange"
        :current-page="currentPage"
        :page-size="pagesize"
        :total="pics.length">
      </el-pagination>
    </el-row>
  </div>
</template>

<script>
import MultiImgUpload from '../common/MultiImgUpload'
export default {
  name: 'PicListIndex',
  components: {MultiImgUpload},
  data () {
    return {
      pics: [],
      picName: '',
      currentPage: 1,
      pagesize: 18
    }
  },
  mounted: function () {
    this.loadPics()
  },
  methods: {
    loadPics () {
      var _this = this
      this.$axios.get('/picsList').then(resp => {
        if (resp && resp.status === 200) {
          _this.pics = resp.data
        }
      })
    },
    handleCurrentChange: function (currentPage) {
      this.currentPage = currentPage
      console.log(this.currentPage)
    },
    deletePicInfo (id) {
      this.$confirm('此操作将永久删除此图片, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.$axios
          .post('/deletePicInfo', {id: id}).then(resp => {
            if (resp && resp.status === 200) {
              this.loadPics()
            }
          })
      }
      ).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
      // alert(id)
    },
    uploadImg () {
      this.loadPics()
      this.picName = this.$refs.mulitiImgUpload.url
      this.$refs.mulitiImgUpload.clear()
    }
  }
}
</script>

3、springboot controller的实现

@RestController
public class PicInfoController {
	@Autowired
	private PicInfoService picInfoService;
	/**
	 * 获取图片列表
	 * @param picInfo
	 * @return
	 * @throws Exception
	 */
	@GetMapping("api/picsList")
	public List<PicInfo> getPicsList(PicInfo picInfo) throws Exception {
		return picInfoService.getPicList(picInfo);
		
	}
	/**
	     * 图片上传处理
	* @param file
	* @param request
	* @return
	* @throws Exception
	*/
	@PostMapping("api/multiPicUpload")
	public String multiPicUpload(MultipartFile file, HttpServletRequest request) throws Exception {
	String folder = "D:/workspace/img";
	File imageFolder = new File(folder);
	File f = new File(imageFolder, getRandomString(6) + file.getOriginalFilename()
	      .substring(file.getOriginalFilename().length() - 4));
	if (!f.getParentFile().exists())
	  f.getParentFile().mkdirs();
	try {
	  file.transferTo(f);
	  System.out.println(file.getOriginalFilename());   
	  
	  String imgURL = "http://localhost:9009/api/file/" + f.getName();
	  //直接保存数据库
	  PicInfo picInfo =  new PicInfo();
	  picInfo.setPicPath(imgURL);
	  picInfo.setPicName(file.getOriginalFilename());
	  picInfoService.addPic(picInfo);
	  return imgURL;
	} catch (IOException e) {
	  e.printStackTrace();
	  return "";
	}
	}
	
	public String getRandomString(int length) {
	String base = "abcdefghijklmnopqrstuvwxyz0123456789";
	Random random = new Random();
	StringBuffer sb = new StringBuffer();
	for (int i = 0; i < length; i++) {
	  int number = random.nextInt(base.length());
	  sb.append(base.charAt(number));
	}
	return sb.toString();
	}
	
	@PostMapping("/api/deletePicInfo")
	public String deletePicInfo(@RequestBody PicInfo picInfo) throws Exception{
		try {
			picInfoService.deletePicById(picInfo);
		}catch(Exception e){
			e.printStackTrace();
		}
		return "success";
	}
	

}

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值