ElementUI+Vue+Springboot实现文件上传之——本地存储

本文要解决的是服务器接受前端上传的文件,并存储在服务器的方案。

一、前端

样式:

		  <el-upload
              action="这里是后端的接口要求完整路径:http://..."
              :on-success="handleSuccess"
              :limit="1"
              :file-list="fileList">
            <el-button size="small">上传</el-button>
            <div slot="tip" class="el-upload__tip">只能上传jpg/png文件,且不超过500kb</div>
          </el-upload>

解释

1.action:文件上传的url

2.:on-success="handleSuccess" 上传成功执行的方法,比如:

   

    handleSuccess(res) {
      console.log(res)
    }

3.:limit="1":最大上传数1

4.:file-list="fileList":展示文件列表,需要在数据区定义fileList

二、后端

1.接口

    //前端页面三要素:表单项type="file" 表单提交方式post 表单的enctype属性为multipart/form-data
    //后端接收文件接口API:MultipartFile(注意名字要一样)
    //文件上传到服务端,有几个内容就形成几个临时文件(供保存),响应完成后就自动删除
    @PostMapping("/接口路径")
    public Result upload(MultipartFile file) throws Exception {
        //文件存盘
        //1.生成文件名uuid:一种固定长度且不重复的随机值,使用 UUID.randomUUID().toString() 可以得到其字符串
        String fileName = UUID.randomUUID().toString();
        //2.获取文件类型
        String originalFilename = file.getOriginalFilename(); // 这里获取原始文件名
        String typeName = originalFilename.substring(originalFilename.lastIndexOf("."));
        //3.拼接
        String fileNewName=fileName+typeName;
        //4.文件存盘
        file.transferTo(new File("文件保存位置"+fileNewName));

        return Result.success();
    }

2.处理跨域问题

引入依赖pom.xml

        <!--跨域配置-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-configuration-processor</artifactId>
            <optional>true</optional>
        </dependency>

在config包下新建CorsConfig类

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;

@Configuration
public class CorsConfig {

    // 当前跨域请求最大有效时长。这里默认1天
    private static final long MAX_AGE = 24 * 60 * 60;

    @Bean
    public CorsFilter corsFilter() {
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        CorsConfiguration corsConfiguration = new CorsConfiguration();
        corsConfiguration.addAllowedOrigin("*"); // 1 设置访问源地址
        corsConfiguration.addAllowedHeader("*"); // 2 设置访问源请求头
        corsConfiguration.addAllowedMethod("*"); // 3 设置访问源请求方法
        corsConfiguration.setMaxAge(MAX_AGE);
        source.registerCorsConfiguration("/**", corsConfiguration); // 4 对接口配置跨域设置
        return new CorsFilter(source);
    }
}

首先,你需要使用 ElementUI 中的 Upload 组件来实现图片上传。具体步骤如下: 1. 在 Vue 组件中引入 ElementUI 的 Upload 组件: ``` <template> <el-upload class="upload-demo" action="/api/upload" :on-success="handleSuccess" :before-upload="beforeUpload" :limit="1" :file-list="fileList" :auto-upload="false"> <el-button slot="trigger" size="small" type="primary">选取文件</el-button> <el-button style="margin-left: 10px;" size="small" type="success" @click="submitUpload">上传到服务器</el-button> <div slot="tip" class="el-upload__tip">只能上传jpg/png文件,且不超过500kb</div> </el-upload> </template> ``` 2. 在 Vue 组件中定义上传文件的处理函数 handleSuccess: ``` <script> export default { data() { return { fileList: [] }; }, methods: { handleSuccess(response, file, fileList) { console.log(response); this.fileList = fileList; }, beforeUpload(file) { const isJPG = file.type === "image/jpeg" || file.type === "image/png"; const isLt500K = file.size / 1024 < 500; if (!isJPG || !isLt500K) { this.$message.error("上传图片只能是 JPG/PNG 格式,且不超过 500KB"); } return isJPG && isLt500K; }, submitUpload() { this.$refs.upload.submit(); } } }; </script> ``` 3. 在后端 SpringBoot 中编写上传文件的 API: ``` @RestController @RequestMapping("/api") public class FileUploadController { @PostMapping("/upload") public ResponseEntity<?> uploadFile(@RequestParam("file") MultipartFile file) { try { // 存储文件 byte[] bytes = file.getBytes(); Path path = Paths.get("uploads/" + file.getOriginalFilename()); Files.write(path, bytes); // 返回成功信息 return ResponseEntity.ok("File uploaded successfully"); } catch (IOException e) { e.printStackTrace(); return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build(); } } } ``` 4. 在前端 Vue 中设置上传文件的 API 地址为后端 SpringBoot 中编写的 API 地址: ``` <el-upload class="upload-demo" action="/api/upload" :on-success="handleSuccess" :before-upload="beforeUpload" :limit="1" :file-list="fileList" :auto-upload="false"> ... </el-upload> ``` 这样,你就可以在前端使用 ElementUI+Vue 实现图片上传,并在后端使用 SpringBoot 接收上传的图片文件了。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值