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