博主
258
258
258
258
专辑

第十七节 SpringBoot+Vue+ElementUI实现文件上传

亮子 2021-07-01 14:27:45 7814 0 0 0

1、SpringBoot接收文件

1)、接收单文件

(1)文件接收函数

    @RequestMapping("fileUpload")
    @ResponseBody
    public ResultResponse fileUpload(@RequestParam("file") MultipartFile file){
        if(file.isEmpty()){
            return ResultResponse.FAILED(-1, "没有文件数据");
        }

        //-- 获取上传的文件名
        String fileName = file.getOriginalFilename();
        int size = (int) file.getSize();
        log.info(fileName + "-->" + size);

        //-- 使用随机文件名,防止文件覆盖
        String suffix = fileName.substring(fileName.lastIndexOf(".")).toLowerCase();
        String newName = UUID.randomUUID().toString();
        newName = newName + suffix;

        File dest = new File(UP_DIR + "/" + newName);
        if(!dest.getParentFile().exists()){
            dest.getParentFile().mkdir();
        }
        try {
            // 保存文件
            file.transferTo(dest);

            // 返回上传的文件信息
            HashMap<String, String> map = new HashMap<>();
            map.put("name", fileName);
            map.put("url", newName);
            return ResultResponse.SUCCESS(map);
        } catch (IllegalStateException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            return ResultResponse.FAILED(-1, "写入失败");
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            return ResultResponse.FAILED(-1, "IO错误");
        }
    }

(2)文件上传大小设置

spring.servlet.multipart.max-file-size=10MB

(3)Vue+ElementUI

<template>
    <div>
        <el-upload
            class="upload-demo"
            action="http://localhost:9000/fileUpload"
            :on-preview="handlePreview"
            :on-remove="handleRemove"
            :before-remove="beforeRemove"
            multiple
            name="file"
            :limit="3"
            :on-exceed="handleExceed"
            :on-success="handleSuccess"
            :file-list="fileList">
            <el-button size="small" type="primary">点击上传</el-button>
            <div slot="tip" class="el-upload__tip">只能上传jpg/png文件,且不超过500kb</div>
        </el-upload>
    </div>
</template>

<script>
export default {
    name: 'Upload',
    data() {
      return {
        fileList: []
      };
    },
    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) {
            console.log(fileList)
            return this.$confirm(`确定移除 ${ file.name }?`);
      },
      handleSuccess(response, file, fileList) {
          console.log("handleSuccess")
          console.log(response)
            console.log(file)
            console.log(fileList)

      }
    }
}
</script>

<style scoped>

</style>

2)接收多文件

(1)文件接收函数

    @PostMapping("/multiUpload")
    @ResponseBody
    public ResultResponse multiUpload(HttpServletRequest request) {
        ArrayList<Object> list = new ArrayList<>();
        HashMap<String, Object> map = new HashMap<>();
        List<MultipartFile> files = ((MultipartHttpServletRequest) request).getFiles("file");
        if(files == null || files.size() <= 0) {
            return ResultResponse.FAILED(-1, "没有文件数据");
        }
        for (int i = 0; i < files.size(); i++) {
            MultipartFile file = files.get(i);
            if (file.isEmpty()) {
                log.info( "上传第" + (i++) + "个文件失败");
            }
            String fileName = file.getOriginalFilename();

            //-- 使用随机文件名,防止文件覆盖
            String suffix = fileName.substring(fileName.lastIndexOf(".")).toLowerCase();
            String newName = UUID.randomUUID().toString();
            newName = newName + suffix;

            File dest = new File(UP_DIR + "/" + newName);
            try {
                file.transferTo(dest);
                log.info("第" + (i + 1) + "个文件上传成功");

                //
                HashMap<String, String> fileMap = new HashMap<>();
                fileMap.put("name", fileName);
                fileMap.put("url", newName);

                list.add(fileMap);
            } catch (IOException e) {
                log.error(e.toString(), e);
                log.info( "上传第" + (i++) + "个文件失败");
            }
        }

        return ResultResponse.SUCCESS(list);
    }

(2)Vue+ElementUI

<template>
    <div>
        <el-upload
            class="upload-demo"
            action="http://localhost:9000/multiUpload"
            :on-preview="handlePreview"
            :on-remove="handleRemove"
            :before-remove="beforeRemove"
            multiple
            name="file"
            :limit="3"
            :on-exceed="handleExceed"
            :on-success="handleSuccess"
            :file-list="fileList">
            <el-button size="small" type="primary">点击上传</el-button>
            <div slot="tip" class="el-upload__tip">只能上传jpg/png文件,且不超过500kb</div>
        </el-upload>
    </div>
</template>

<script>
export default {
    name: 'Upload',
    data() {
      return {
        fileList: []
      };
    },
    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) {
            console.log(fileList)
            return this.$confirm(`确定移除 ${ file.name }?`);
      },
      handleSuccess(response, file, fileList) {
          console.log("handleSuccess")
          console.log(response)
            console.log(file)
            console.log(fileList)

      }
    }
}
</script>

<style scoped>

</style>

2、SpringBoot文件回显

上传的文件如果想要回显或者下载,需要对文件的存储目录进行静态资源的映射,可以通过两种方法解决:

方法1: 在工程中添加代码

@Slf4j
@Configuration
public class WebMvcConfiguration implements WebMvcConfigurer {

    private final String UPLOAD_DIR = "E:/test";


    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        String location = "file:///" + UPLOAD_DIR;
        log.info("localtion:"+location);

        registry.addResourceHandler("/storage/thumbnails/**")
                .addResourceLocations(location + "/storage/thumbnails/");
    }
}

方法2:在配置文件中增加配置

  • application.properties
# resource
spring.resources.static-locations=classpath:/static/,file:E:\\opt\\img\\
spring.mvc.static-path-pattern=/img/**
  • application.yml
spring:
  resources:
    static-locations: classpath:/static/,file:D:\\img\\