Vue Element UI + SpringBoot文件上传和下载

avatar 2020年5月18日17:06:27 评论 95 views

本文介绍 Vue Element UI 下的文件上传,后端采用SpringBoot

Element UI 上传文档地址:点此

代码地址:https://github.com/saysky/petition-system-server

一、效果图

1、上传

点击上传按钮弹出选择框,选择文件后,请求上传接口,然后返回文件URL数据,在输入框里显示

2、下载

点击下载按钮,浏览器能自动下载文件

 

二、上传代码

1.上传

<template>
    <div>
        <el-row>
            <el-col :span="12">
                <el-form ref="form" label-width="100px">
                    <el-form-item prop="attachmentUrl" label="附件">
                        <el-input v-model="attachmentUrl"></el-input>
                        <el-upload
                            class="upload-demo"
                            action="/api/file/upload"
                            :limit="1"
                            :show-file-list="false"
                            :file-list="fileList"
                            :on-success="uploadSuccess">
                            <el-button size="small" type="primary">点击上传</el-button>
                        </el-upload>
                    </el-form-item>
                </el-form>
            </el-col>
        </el-row>
    </div>
</template>

<script>

    export default {
        data() {
            return {
                fileList: [],
                attachmentUrl: ''
            }
        },
        methods: {
            uploadSuccess: function (response, file, fileList) {
                console.log(response);
                this.attachmentUrl = response.path;
            }

        },
        //初始化
        created() {
        }
    }
</script>

<style>
    
</style>

 

 

2.下载

下载完全是前台获取到文件URL后,新打开一个窗口,不涉及再次请求后台下载操作

<template>
    <div>
        <el-row>
            <el-col :span="12">
                <el-form ref="form" label-width="100px">
                    <el-form-item prop="attachmentUrl" label="附件">
                        <el-input v-model="attachmentUrl" disabled></el-input>
                        <el-button size="mini" type="primary" @click="download()">下载
                        </el-button>
                    </el-form-item>

                </el-form>
            </el-col>
        </el-row>
    </div>
</template>

<script>

    export default {
        data() {
            return {
                // 这里为了简化其他代码,直接将URL写死在这里。正常是通过请求后台接口,然后赋值
                attachmentUrl: 'https://liuyanzhao.com/wp-content/uploads/2020/05/WX20200518-142554@2x.png'
            }
        },
        methods: {
            download() {
                let a = document.createElement('a')
                a.target = '_blank';
                a.href = this.form.attachmentUrl;
                a.click();
            }
        },
        //初始化
        created() {
        }
    }
</script>

<style>

</style>

 

三、后端代码

1、上传接口代码如下

@PostMapping(value = "/api/file/upload", produces = {"application/json;charset=UTF-8"})
@ResponseBody
public Map<String, Object> uploadFile(@RequestParam("file") MultipartFile file) {
    Map<String, Object> map = new HashMap<>();
    String path = null;
    try {
        path = FileUtil.upload(file);
    } catch (Exception e) {
        e.printStackTrace();
    }
    map.put("path", prefix + path);
    return map;
}

 

2、FileUtil.java

package com.example.sens.util;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.text.StrBuilder;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;

/**
 * @author 言曌
 * @date 2020/3/8 5:45 下午
 */
public class FileUtil {

    /**
     * 上传文件返回URL
     *
     * @param file
     * @return
     */
    public static String upload(MultipartFile file) throws Exception {
        String path = "";
        try {
            //用户目录
            final StrBuilder uploadPath = new StrBuilder(System.getProperties().getProperty("user.home"));
            uploadPath.append("/sens/upload/" + DateUtil.thisYear()).append("/").append(DateUtil.thisMonth() + 1).append("/");
            final File mediaPath = new File(uploadPath.toString());
            if (!mediaPath.exists()) {
                if (!mediaPath.mkdirs()) {
                    throw new Exception("上传失败");
                }
            }

            //不带后缀
            String nameWithOutSuffix = file.getOriginalFilename().substring(0, file.getOriginalFilename().lastIndexOf('.')).replaceAll(" ", "_").replaceAll(",", "");

            //文件后缀
            final String fileSuffix = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf('.') + 1);

            //带后缀
            String fileName = nameWithOutSuffix + "." + fileSuffix;

            //判断文件名是否已存在
            File descFile = new File(mediaPath.getAbsoluteFile(), fileName);
            int i = 1;
            while (descFile.exists()) {
                String newNameWithOutSuffix = nameWithOutSuffix + "(" + i + ")";
                descFile = new File(mediaPath.getAbsoluteFile(), newNameWithOutSuffix + "." + fileSuffix);
                i++;
            }
            file.transferTo(descFile);

            //文件原路径
            final StrBuilder fullPath = new StrBuilder(mediaPath.getAbsolutePath());
            fullPath.append("/");
            fullPath.append(nameWithOutSuffix + "." + fileSuffix);

            //压缩文件路径
            final StrBuilder fullSmallPath = new StrBuilder(mediaPath.getAbsolutePath());
            fullSmallPath.append("/");
            fullSmallPath.append(nameWithOutSuffix);
            fullSmallPath.append("_small.");
            fullSmallPath.append(fileSuffix);

            //映射路径
            final StrBuilder filePath = new StrBuilder("/upload/");
            filePath.append(DateUtil.thisYear());
            filePath.append("/");
            filePath.append(DateUtil.thisMonth() + 1);
            filePath.append("/");
            filePath.append(nameWithOutSuffix + "." + fileSuffix);
            path = filePath.toString();

        } catch (IOException e) {
            e.printStackTrace();
        }
        return path;
    }
}

 

这里使用了  hutool 依赖

<!-- hutool工具包 -->
<dependency>
  <groupId>cn.hutool</groupId>
  <artifactId>hutool-all</artifactId>
  <version>4.1.13</version>
</dependency>

 

3、静态资源映射

MvcConfig.java

package com.example.sens.config;

import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.*;

/**
 * <pre>
 *     拦截器,资源路径配置
 * </pre>
 */
@Slf4j
@Configuration
public class MvcConfig implements WebMvcConfigurer {

    /**
     * 配置静态资源路径
     *
     * @param registry registry
     */
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/static/**")
                .addResourceLocations("classpath:/static/");
        registry.addResourceHandler("/upload/**")
                .addResourceLocations("file:///" + System.getProperties().getProperty("user.home") + "/sens/upload/");
        registry.addResourceHandler("/favicon.ico")
                .addResourceLocations("classpath:/static/images/favicon.ico");
    }


    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**")
                .allowCredentials(true)
                .allowedHeaders("*")
                .allowedOrigins("*")
                .allowedMethods("*");
    }

}

 

完整代码可以联系博主

后端代码地址:https://github.com/saysky/petition-system-server

 

  • 微信
  • 交流学习,有偿服务
  • weinxin
  • 博客/Java交流群
  • 资源分享,问题解决,技术交流。群号:590480292
  • weinxin
avatar

发表评论

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: