使用Element组件:
前端代码:
<div style="display: flex;justify-content: flex-end">
<el-upload
class="upload-demo"
action="/api/filesystem/uploadCourseWare"
:limit="picmax"
:data="uploadval"
:headers="importHeaders"
:on-success="success"
:file-list="fileList"
name="file">
<el-button size="small" type="primary">点击上传</el-button>
</el-upload>
</div>
其中 :headers="importHeaders"中包含请求上传所要附带的头信息,在进入页面时执行mounted()钩子方法获得头信息,这里获得的头信息为当前上传文件的用户信息(这里用户的信息存储在jwt令牌中):
export default{
data(){
return{
importHeaders:{},
picmax:1,//最大上传文件的数量
uploadval:{filetag:"courseware"},//上传提交的额外的数据 ,将uploadval转成key/value提交给服务器
fileList:[],
}
},
methods:{
//获得请求头
getHeader(){
let jwt = utilApi.getJwt();
this.importHeaders.Authorization ='Bearer '+jwt;
}
}
mounted(){
this.getHeader();
}
}
后端代码:
@PostMapping("/uploadCourseWare")
public UploadFileResult uploadWPF(@RequestParam("file")MultipartFile multipartFile) {
String userId = this.getUserId();
return fileSystemService.uploadCourseWare(multipartFile,userId);
}
getUserId方法用于解析请求的header中的用户信息,并取出用户的userId,相关方法及工具类如下所示:
//获取当前用户的userId
private String getUserId(){
//获取当前用户信息
XcOauth2Util xcOauth2Util = new XcOauth2Util();
XcOauth2Util.UserJwt jwt = xcOauth2Util.getUserJwtFromHeader(request);
//当前用户的id
String userId = jwt.getId();
return userId;
}
public class XcOauth2Util {
public UserJwt getUserJwtFromHeader(HttpServletRequest request){
Map<String, String> jwtClaims = Oauth2Util.getJwtClaimsFromHeader(request);
if(jwtClaims == null || StringUtils.isEmpty(jwtClaims.get("id"))){
return null;
}
UserJwt userJwt = new UserJwt();
userJwt.setId(jwtClaims.get("id"));
userJwt.setName(jwtClaims.get("name"));
userJwt.setCompanyId(jwtClaims.get("companyId"));
userJwt.setUtype(jwtClaims.get("utype"));
userJwt.setUserpic(jwtClaims.get("userpic"));
return userJwt;
}
@Data
public class UserJwt{
private String id;
private String name;
private String userpic;
private String utype;
private String companyId;
}
}
public class Oauth2Util {
public static Map<String,String> getJwtClaimsFromHeader(HttpServletRequest request) {
if (request == null) {
return null;
}
//取出头信息
String authorization = request.getHeader("Authorization");
if (StringUtils.isEmpty(authorization) || authorization.indexOf("Bearer") < 0) {
return null;
}
//从Bearer 后边开始取出token
String token = authorization.substring(7);
Map<String,String> map = null;
try {
//解析jwt
Jwt decode = JwtHelper.decode(token);
//得到 jwt中的用户信息
String claims = decode.getClaims();
//将jwt转为Map
map = JSON.parseObject(claims, Map.class);
} catch (Exception e) {
e.printStackTrace();
}
return map;
}
}