效果展示:

 

实现思路: 基于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();
    }
	
}

 

Logo

前往低代码交流专区

更多推荐