elementui springboot实现照片墙

该代码片段展示了前端使用ElementUI的`el-upload`组件进行图片上传,包括文件类型和大小限制,以及后端使用SpringBoot接收文件,保存并返回图片URL的过程。同时,还包括了图片列表的获取和图片删除功能,以及跨域配置。
摘要由CSDN通过智能技术生成
 <el-upload
          ref="upload"
          :before-upload="uploadSectionFile"
          :action="fileupaction"
          list-type="picture-card"
          :on-remove="handleRemove"
          :on-success="success"
          :file-list="filelist"
          :on-change="changeSectionFile"
        >
          <i class="el-icon-plus" />
        </el-upload>
        <el-dialog :visible.sync="dialogVisible">
          <img width="100%" :src="dialogImageUrl" alt="">
        </el-dialog>

 handleRemove(file, fileList) {
      console.log(this.imgs)
      if (this.$route.query.id != null) {
        const url = file.url.replace('http://localhost:8080/', '')
        this.imgs = this.imgs.replace(url + ',', '')
      } else {
        this.imgs = this.imgs.replace(file.response.data + ',', '')
      }
      console.log(this.imgs)
    },
    success(response, file) {
      if (response.code === 200) {
        this.dialogImageUrl = response.data
        this.imgs = this.imgs + this.dialogImageUrl + ','
      }
      console.info(this.imgs)
    },
    uploadSectionFile(file) {
      var testmsg = file.name.substring(file.name.lastIndexOf('.') + 1).toLocaleLowerCase()
      const extension =
        testmsg === 'jpg' ||
        testmsg === 'png' ||
        testmsg === 'jpeg'
      const isLt2M = file.size / 1024 / 1024 < 1

      if (!extension) {
        this.$message.error('上传头像图片只能是 JPG/PNG 格式!')
        return false
      } else if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!')
        return false
      } else {
        return extension && isLt2M
      }
    },
    changeSectionFile(file) {
      var testmsg = file.name.substring(file.name.lastIndexOf('.') + 1).toLocaleLowerCase()
      const extension =
        testmsg === 'jpg' ||
        testmsg === 'png' ||
        testmsg === 'jpeg'
      const isLt2M = file.size / 1024 / 1024 < 2
      return extension && isLt2M
    },
//获取图片列表
 getImgsList({ id: this.$route.query.id}).then(function(res) {
        console.info(res)
        const imgarray = []
        res.data.forEach(function(data, index) {
          imgarray.push({ name: index, url: 'http://localhost:8080/' + data.photo })
          _this.imgs += data.photo + ','
        })
        _this.filelist = imgarray
      })
package com.lostperson.controller;

import com.lostperson.vo.AjaxResult;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.system.ApplicationHome;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

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

@RestController
@RequestMapping("/file")
public class FileUploadController {
    private String imgString;

    @Value("${image.uploadurl}")
    private String uppath;

    @PostMapping("/upload")
    public AjaxResult uploadFile(@RequestParam("file") MultipartFile file) {
        // 判断文件是否为空
        if (file.isEmpty()) {
            return AjaxResult.error("上传文件不能为空");

        }
        // 获取传过来的文件名字
        String OriginalFilename = file.getOriginalFilename();
        //判断文件类型
        String type = OriginalFilename.substring(OriginalFilename.lastIndexOf(".") + 1).toLowerCase();
        if (!type.equals("jpg") && !type.equals("png") && !type.equals("jpeg")) {
            return AjaxResult.error("不是图片");
        }

//        //获取jar包所在目录
//        ApplicationHome h = new ApplicationHome(getClass());
//        File jarF = h.getSource();
//        //在jar包所在目录下生成一个upload文件夹用来存储上传的图片
//        String filePath = jarF.getParentFile().toString() + "/classes/static/upload/";
        String filePath = uppath + "/upload/";
        // 保存头像文件的文件夹
        File dir = new File(filePath);
        if (!dir.exists()) {
            dir.mkdirs();
        }
        // 为了防止重名覆盖,获取系统时间戳+原始文件的后缀名
        String fileName = System.currentTimeMillis() + "." + OriginalFilename.substring(OriginalFilename.lastIndexOf(".") + 1);
        File dest = new File(filePath + fileName);
        String imgString = "/upload/" + fileName;
        // 判断文件是否存在
        if (!dest.getParentFile().exists()) {
            // 不存在就创建一个
            dest.getParentFile().mkdirs();
        }
        try {
            // 上传
            file.transferTo(dest);
            return AjaxResult.success("上传成功", imgString);
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.error("上传失败");
        }
    }

    @PostMapping("/uploads")
    public AjaxResult uploadFiles(@RequestParam("files") MultipartFile[] files) {
        String img = "";
        //获取jar包所在目录
        ApplicationHome h = new ApplicationHome(getClass());
        File jarF = h.getSource();
        //在jar包所在目录下生成一个upload文件夹用来存储上传的图片
        String filePath = uppath+ "/upload/";
        File fileDir = new File(filePath);
        if (!fileDir.exists() && !fileDir.isDirectory()) {
            fileDir.mkdirs();
        }
        if (files != null && files.length > 0) {
            for (int i = 0; i < files.length; i++) {
                String OriginalFilename = files[i].getOriginalFilename();
                System.out.println("文件名为:" + OriginalFilename);
                String fileName = System.currentTimeMillis() + "." + OriginalFilename.substring(OriginalFilename.lastIndexOf(".") + 1);
                File dest = new File(filePath + fileName);
                imgString = "/upload/" + fileName;
                try {
                    files[i].transferTo(dest);
                    if (img.equals("")) {
                        img = imgString;
                    } else {
                        img = img + ";" + imgString;
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                    return AjaxResult.warn(e.getMessage());
                }
            }
        } else {
            return AjaxResult.warn("文件为0");
        }
        return AjaxResult.success("上传成功", img);
    }
}

package com.lostperson.config;

import com.lostperson.interceptor.AuthenticationInterceptor;
import org.springframework.beans.factory.annotation.Value;
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;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport;

@Configuration
public class WebConfig extends WebMvcConfigurationSupport {
    @Value("${image.uploadurl}")
    private String uppath;
    @Override
    protected void addInterceptors(InterceptorRegistry registry) {
        // 拦截所有请求,通过判断是否有 @LoginRequired 注解 决定是否需要登录
        registry.addInterceptor(authenticationInterceptor())
                .addPathPatterns("/admin/**","/getInfo");
    }
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
//        registry.addResourceHandler("/**").addResourceLocations(
//                "classpath:/static/");
        registry.addResourceHandler("/upload/**").addResourceLocations(
                "file:"+uppath+"/upload/");
    }
    /**
     * 跨越配置
     * 改用过滤器CorsFilter 来配置跨域,由于Filter的位置是在Interceptor之前的,问题得到解决:
     */
    @Bean
    public CorsFilter corsFilter() {
        CorsConfiguration config = new CorsConfiguration();
        // 设置允许跨域请求的域名
        config.addAllowedOrigin("*");
        // 是否允许证书 不再默认开启
        // config.setAllowCredentials(true);
        // 设置允许的方法
        config.addAllowedMethod("*");
        // 允许任何头
        config.addAllowedHeader("*");
        config.addExposedHeader("Authorization");
        UrlBasedCorsConfigurationSource configSource = new UrlBasedCorsConfigurationSource();
        configSource.registerCorsConfiguration("/**", config);
        return new CorsFilter(configSource);
    }

    @Bean
    public AuthenticationInterceptor authenticationInterceptor() {
        return new AuthenticationInterceptor();
    }
}

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值