前言:
写项目时突然要跨域上传文件,之前一直是存入到本地文件夹中,但是在尝试了好几个办法后找到了一个办法.
在SpringBoot项目中的application.yml文件中设置如下参数:
spring:
servlet:
multipart:
enabled: true
max-file-size: 30MB
max-request-size: 30MB
file:
upload:
path=http://localhost:8000/upload/:
引入跨服器上传所需要的jar包坐标
<dependency>
<groupId>com.sun.jersey</groupId>
<artifactId>jersey-core</artifactId>
<version>1.18.1</version>
</dependency>
<dependency>
<groupId>com.sun.jersey</groupId>
<artifactId>jersey-client</artifactId>
<version>1.18.1</version>
</dependency>
Controller中:
@Value("${file.upload.path}")
private String path;
@PostMapping(path = "/fileupload")
public CommonResult fileupload(@RequestParam("file") MultipartFile file, @RequestHeader("token")String token){
CommonResult commonResult=null;
//获取照片的名称
String oldFileName=file.getOriginalFilename();
//获取新的照片名称,防止照片重名
String newFileName= StringUtil.newFileName(oldFileName);
//从token中获取登录人Id
DecodedJWT tokenInfo = JWTUtil.getTokenInfo(token);//从token中解析用户的数据
Integer id = tokenInfo.getClaim("id").asInt();
try {
// 创建客户端的对象
Client client = Client.create();
// 和图片服务器进行连接
WebResource webResource = client.resource(path + newFileName);
webResource.put(file.getBytes());
//保存图片与账号的关系
Admin admin1=new Admin();
admin1.setId(id);
admin1.setNewFileName(newFileName);
admin1.setOldFileName(oldFileName);
adminService.updateAdminFile(admin1);
commonResult=new CommonResult(200,"上传成功",admin1);
} catch (IOException e) {
e.printStackTrace();
commonResult=new CommonResult(500,"服务器忙,请稍后重试",null);
}
return commonResult;
}
vue代码块:
handleAvatarChange(file) {
var _this=this;
this.imageUrl = URL.createObjectURL(file.raw);
var formData = new FormData();
formData.append("file", file.raw);
this.$http.post("admin/fileupload",formData).then(function(resp){
//上传成功后,更新头像,刷新页面
})
},