SpringBoot ElementUI 文件上传和预览

效果展示:

 

实现思路: 基于ElementUI 文件上传控件el-upload,实现文件简单上传,基于el-upload的on-preview 预览属性实现上传文件预览。

 

VUE + ElementUI源码:


<template>
<div>
   		 <el-upload
  class="upload-demo"
  action="http://localhost:9097/api/file/upload"
  :on-preview="handlePreview"
  :on-remove="handleRemove"
  :before-remove="beforeRemove"
  multiple
  :limit="3"
  :on-exceed="handleExceed"
  list-type="picture"
  :file-list="fileList">
  <el-button size="small" type="primary">点击上传</el-button>
  <div slot="tip" class="el-upload__tip">只能上传jpg/png文件,且不超过500kb</div>
</el-upload>
<el-dialog :visible.sync="dialogVisible" append-to-body>
  <img width="100%" fit="contain" :src="dialogImageUrl" alt="">
</el-dialog>
</div>
</template>

<script>
export default {
    data() {
      return {
        dialogImageUrl: "",
        dialogVisible: false,
        fileList: []
      };
    },
    methods: {
      handleRemove(file, fileList) {
        console.log(file, fileList);
      },
      handlePreview(file) {
        console.log(file);
        this.dialogImageUrl = file.url;
        this.dialogVisible = true;
      },
      handleExceed(files, fileList) {
        this.$message.warning(`当前限制选择 3 个文件,本次选择了 ${files.length} 个文件,共选择了 ${files.length + fileList.length} 个文件`);
      },
      beforeRemove(file, fileList) {
        return this.$confirm(`确定移除 ${ file.name }?`);
      }
    }
  }
</script>
<style>
</style>

SpringBoot源码:

package com.zzg.controller;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import javax.servlet.http.HttpServletResponse;

import org.apache.commons.io.IOUtils;
import org.springframework.http.HttpMethod;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.zzg.common.model.Result;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;

@Controller
@RequestMapping("/api/file")
@CrossOrigin
@Api(value = "模拟测试Controlle", tags = "模拟测试操作服务")
public class TestFileUpload {
	// 上传图片更路径
	private  final static String rootPath = "D:/attachment/";
	
	@ApiOperation(httpMethod = "POST", value = "模拟文件上传")
	@RequestMapping(value = "/upload",method = { RequestMethod.POST})
	@ResponseBody
	public Object uploadFile(@RequestParam("file") MultipartFile[] file){
        File fileDir = new File(rootPath);
        if (!fileDir.exists() && !fileDir.isDirectory()) {
            fileDir.mkdirs();
        }
        try {
            if (file != null && file.length > 0) {
                for(int i = 0;i<file.length;i++){
                    try {
                        //以原来的名称命名,覆盖掉旧的,这里也可以使用UUID之类的方式命名,这里就没有处理了
                        String storagePath = rootPath+file[i].getOriginalFilename();
                        System.out.println("上传的文件:" + file[i].getName() + "," + file[i].getContentType() + "," + file[i].getOriginalFilename()
                                +",保存的路径为:" + storagePath);
                        // 3种方法: 第1种
//                        Streams.copy(multipartFiles[i].getInputStream(), new FileOutputStream(storagePath), true);
                        // 第2种
//                        Path path = Paths.get(storagePath);
//                        Files.write(path,multipartFiles[i].getBytes());
                        // 第3种
                        file[i].transferTo(new File(storagePath));
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
 
        } catch (Exception e) {
            e.printStackTrace();
        }
        //前端可以通过状态码,判断文件是否上传成功
        return  Result.ok();
    }
	
}

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值