前言
        看过我前几篇写的文章都知道,我做的项目属于前后端分离,所以必然要联系到ajax(axios)请求跨域问题,因此有些问题是建立在跨域的基础上出现的。利用Element进行文件上传(自我感觉element-ui用于PC端开发比较合适唉),有几个注意的点。

爬坑

        1、跨域访问后端的路径,action一定要加api;否则跨域访问会失败,然后就报错。
        2、action还可以传其他参数给后台,如果需要可以在后面添加,如action=" /toUpdateAvatar?userid=1"
        3、通过在上传标签里添加accept可以限制传入的文件类型,如添加accept=" .jpg , .png ",系统只会让你选择这些类型的文件。
        4、在后端将文件上传到项目上时注意路径问题,暂时还没有想到如何以相对路径的方式保存到项目里,这里我用的是绝对路径。
        5、此时,如果文件会顺利保存到后端服务器,但是,访问时却访问不到,所以我想应该是后端服务器没有将刚刚上传的文件部署到Tomcat上叭,所以此时的情况才会是:必须重启后端服务器才能将文件全部部署到Tomcat上,从而访问到文件,此时就需要配置映射文件来解决问题了。

前端

        组件|Element
在这里插入图片描述

<template>
	<div>
		<el-upload
		  class="avatar-uploader"
		  :action="/api/toUpdateAvatar?userid=1"
		  :show-file-list="false"
		  accept=".jpg,.png"
		  :on-success="handleAvatarSuccess"
		  :before-upload="beforeAvatarUpload">
		  <img v-if="imageUrl" :src="imageUrl" class="avatar">
		  <i v-else class="el-icon-plus avatar-uploader-icon"></i>
		</el-upload>
	</div>
</template>
<script>
	export default{
		data() {
	      return {
	        imageUrl: '',
	      };
	    },
	    methods: {
	      handleAvatarSuccess(res, file) {
	        this.imageUrl = URL.createObjectURL(file.raw);
	      },
	      beforeAvatarUpload(file) {
			//在头像上传之前需要做的判断,如判断文件格式
	        const isJPG = file.type === 'image/jpeg';
	        const isLt2M = file.size / 1024 / 1024 < 2;
	      }
	    }
	}
</script>
<style>
  .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
  }
  .avatar {
    width: 178px;
    height: 178px;
    display: block;
  }
</style>

后端

	/**
     * 上传头像
     * @param
     * @param file
     * @return
     * @throws Exception
     */
    @RequestMapping("/toUploadAvatar")
    public MessageJson updatAvatar(User user,MultipartFile file) throws Exception{
        //判断文件类型
        String pType=file.getContentType();
        pType=pType.substring(pType.indexOf("/")+1);

        if("jpeg".equals(pType)){
            pType="jpg";
        }
        long time=System.currentTimeMillis();
        //这里我采用绝对路径
        String path="D:/(项目路径)/src/main/resources/static/images/avatar"+time+"."+pType;
		
        try{
            file.transferTo(new File(path));
            //文件路径保存到数据库中从而读取
            userService.addVatar("http://192.168.191.3:8081/"+path.substring(path.indexOf("images/")),user);
        }catch (Exception e){
            e.printStackTrace();
        }
        return new MessageJson(SUCCESS,null);
    }

解决上传文件访问不到的问题

        访问不到刚刚上传的文件,主要是因为服务器并没有把刚刚的文件部署的Tomcat上,因此要配置文件访问的映射,具体操作如下:
        1: 创建配置文件类,FileUploadConfig.java
        2: 添加@Configuration注解,并实现WebMvcConfigurer接口
        3: 重写WebMvcConfigurer的addResourcesHandlers方法
        4: 配置映射,且映射路径以file开头
        具体操作如下

@Configuration
public class FileUploadConfig implements WebMvcConfigurer {
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/images/**").
                addResourceLocations("file:///D:/(项目存放路径)/src/main/resources/static/images/");
                //如果不知道如何以file开头就用浏览器打开该图片
    }
}

        亲测可用~~

Logo

前往低代码交流专区

更多推荐