效果:
uni-app
<template>
<view class="auth" :style="{ paddingTop: systemInfo.navigationBarHeight +'px' }">
<view class="top">
<view style="padding-right: 10px; display: inline-block;" @click="exit">
<text class="iconfont icon-delete" style="color: #212121;font-size: 19px;"></text>
</view>
</view>
<view class="center">
<view style="height: 60%; flex-direction: column;" class="flex-center">
<text class="iconfont icon-PC" style="font-weight: 100; font-size: 150px; color: #8d8d8d;"></text>
<text style="margin-top: 10px; color: #333333; font-size: 38rpx; font-weight: 500" v-if="status !== 'success'">登录 PC 正域绿能</text>
<text style="margin-top: 10px; color: #333333; font-size: 38rpx; font-weight: 500" v-else>已成功认证</text>
</view>
<view style="height: 40%; flex-direction: column;" class="flex-center">
<navigator open-type="exit" target="miniProgram" v-if="status === 'success'">
<button
type="default"
style="padding: 0 150rpx; color: #24b155">我知道了</button>
</navigator>
<template v-else>
<button type="primary" :loading="loading" @tap="handleUserAuth"
style="background-color: #27c05e; padding: 0 150rpx">登录</button>
<text @tap="exit" style="margin-top: 25px; color: #62708e; font-size: 17px">取消登录</text>
<template v-if="!isRelease">
<uni-easyinput v-model="scene" :inputBorder="true" style="margin-top: 10px" placeholder="场景值"
clearable />
<text @tap="load" style="margin-top: 25px; color: #62708e; font-size: 17px">模拟进入</text>
</template>
</template>
</view>
</view>
</view>
</template>
<script>
import {
mapGetters
} from 'vuex'
import {
handleUserScan,
handleUserCancel,
handleUserAuth
} from '@/common/api/user'
import { isRelease } from '@/common/env'
export default {
data() {
return {
isRelease: isRelease,
loading: false,
// 用户信息
authInfo: {},
// 用户唯一标识
openid: '',
// 场景值
scene: '',
// 扫描状态,用于退出登录界面
status: 'wait'
};
},
computed: {
...mapGetters(['systemInfo']),
},
async onLoad(options) {
const _t = this;
if(!options.scene && _t.isRelease) return _t.$mRouter.redirectTo("/pages/transfer/transfer")
// 对scene进行解码
const scene = decodeURIComponent(options.scene) || ""
// const scene = _t.scene
console.log('scene >>>', scene)
_t.scene = scene
const code = await _t.getCode();
// 1、修改 认证状态为 已扫码
const res = await handleUserScan({
scene: scene,
code: code
})
console.log("修改状态情况", res)
const {
code: resCode,
data
} = res.data;
if (resCode === 200) _t.authInfo = data;
},
methods: {
async load() {
const _t = this;
// 对scene进行解码
// const scene = decodeURIComponent(options.scene)
const scene = _t.scene
console.log('scene >>>', scene)
_t.scene = scene
const code = await _t.getCode();
// 1、修改 认证状态为 已扫码
const res = await handleUserScan({
scene: scene,
code: code
})
console.log("修改状态情况", res)
const {
code: resCode,
data
} = res.data;
if (resCode === 200) _t.authInfo = data;
},
// 获取微信code
async getCode() {
const code = await this.login();
return code ? code : '';
},
// 微信登录
login() {
return new Promise(resolve => {
uni.login({
provider: 'weixin',
success(loginRes) {
console.log("获取code成功")
resolve(loginRes.code)
},
fail(err) {
resolve('');
}
});
})
},
// 点击认证时绑定的事件,获取用户信息
async handleUserAuth() {
const _t = this;
_t.loading = true;
const code = await _t.getCode();
console.log("权限信息:", _t.authInfo);
const res = await handleUserAuth({
nickname: _t.authInfo.username || "",
openid: _t.authInfo.wechatOpenid || "",
avatar: _t.authInfo.avatar || "",
scene: _t.scene || ""
})
console.log("认证情况", res);
const {
success,
code: resCode,
message
} = res.data
if (resCode === 200) {
_t.status = 'success'
_t.$cu.showToast("认证成功");
}
_t.loading = false;
},
// 用户点击 取消认证,或已认证,返回微信
async exit() {
const _t = this;
// 如果状态为 wait 说明用户 未认证点击了取消登录
if (_t.status === 'wait') {
// 发送请求,将数据库状态修改为 cancel,再执行退出
const res = await handleUserCancel({
scene: _t.scene
});
console.log("取消认证情况", res);
if (res.data.code === 200) {
console.log("退出小程序");
// 执行退出小程序
wx.exitMiniProgram({
success: res => {
console.log(res)
}
})
}
} else {
//否则,说明已认证,直接退出小程序即可
console.log("退出小程序");
wx.exitMiniProgram({
success: res => {
console.log(res)
}
})
}
}
}
}
</script>
<style lang="scss">
.auth {
width: 100%;
height: 100vh;
background-color: #ededed;
box-sizing: border-box;
position: relative;
padding: 0 20rpx;
.top {
width: 100%;
}
.center {
width: 100%;
height: 75vh;
margin-top: 5vh;
border-radius: 10px;
background-color: #fff;
}
}
</style>
springboot
ScanStatus
package com.bn.ies.appapi.scanLogin.constant;
import lombok.AllArgsConstructor;
import lombok.Getter;
/**
* 登录扫码状态
*
* @author 蓝之静云
*/
@AllArgsConstructor
@Getter
public enum ScanStatus {
/**
* 等待扫码
*/
WAIT("wait"),
/**
* 已扫码
*/
ING("ing"),
/**
* 认证成功
*/
SUCCESS("success"),
/**
* 取消认证
*/
CANCEL("cancel");
/**
* 扫码状态
*/
private String status;
}
LoginController
package com.bn.ies.appapi.scanLogin.controller;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.bn.ies.appapi.scanLogin.constant.ScanStatus;
import com.bn.ies.appapi.scanLogin.pojo.dto.Login;
import com.bn.ies.appapi.scanLogin.pojo.dto.User;
import com.bn.ies.appapi.scanLogin.service.LoginService;
import com.bn.ies.appapi.scanLogin.service.UserService;
import com.bn.ies.appapi.system.utils.WeixinUtils;
import com.bn.ies.base.config.FileProperties;
import com.bn.ies.base.entity.Result;
import com.bn.ies.base.entity.po.SysUser;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
/**
* @author 蓝之静云
*/
@RestController
@RequestMapping("/login")
public class LoginController {
@Autowired
private LoginService loginService;
@Autowired
private UserService userService;
@Autowired
private FileProperties properties;
/**
* 创建 login 数据
*
* @return 文件名
*/
@PostMapping("create")
public String createUserLogin(@RequestBody Login login){
return loginService.createAndGetQrcodeFile(login.getScene());
}
@GetMapping("/qrcode/{name:.+}")
@ApiOperation("根据名称获取图片资源")
public void getImg(@PathVariable("name") String name, HttpServletResponse response) throws Exception {
ServletOutputStream outputStream = null;
FileInputStream inputStream = null;
try {
String imgPath = properties.getPath().getQrCode() + File.separator + name;
inputStream = new FileInputStream(imgPath);
response.setContentType("image/" + name.split("\\.")[1]);
outputStream = response.getOutputStream();
int len;
byte[] buffer = new byte[4096];
while ((len = inputStream.read(buffer)) != -1) {
outputStream.write(buffer, 0, len);
}
outputStream.flush();
} catch (Exception e) {
e.printStackTrace();
} finally {
outputStream.close();
inputStream.close();
}
}
/**
* 修改扫码状态为 已扫码
*
* @param login 登录信息
*/
@PostMapping("scan")
public Result<?> userScanQrcode(Login login, HttpServletRequest request) throws Exception{
JSONObject json = WeixinUtils.getSession(login.getCode());
if (json == null) {
return Result.fail("获取openid失败");
}
String wechatOpenid = json.getString("openid");
// 通过openid查询用户信息返回
SysUser userInfo = loginService.getUserInfoByOpenid(wechatOpenid, request);
userInfo.setWechatOpenid(wechatOpenid);
// 更新登录表
login.setAvatar(userInfo.getAvatar());
login.setStatus(ScanStatus.ING.getStatus());
QueryWrapper<Login> wrapper = new QueryWrapper<>();
wrapper.eq("scene", login.getScene());
loginService.update(login, wrapper);
return Result.success(userInfo);
}
/**
* 用户点击确认
*
* @param user 执行的用户
* @param login 登录信息
*/
@PostMapping("auth")
public Result<?> userAuthWebPro(User user, Login login) {
// 更新/添加 用户信息
getUserInfo(user);
QueryWrapper<User> wrapper = new QueryWrapper<>();
wrapper.eq("openid", user.getOpenid());
User one = userService.getOne(wrapper);
// 更改 扫码状态
login.setStatus(ScanStatus.SUCCESS.getStatus());
login.setUserid(one.getId());
QueryWrapper<Login> wrapper1 = new QueryWrapper<>();
wrapper1.eq("scene", login.getScene());
loginService.update(login, wrapper1);
return Result.success("认证成功");
}
/**
* 用户取消认证
*
* @param params
*/
@PostMapping("cancel")
public Result<?> userCancelAuth(@RequestBody JSONObject params) {
// 修改状态为 cancel
Login login = new Login();
login.setStatus(ScanStatus.CANCEL.getStatus());
QueryWrapper<Login> wrapper = new QueryWrapper<>();
wrapper.eq("scene", params.getString("scene"));
loginService.update(login, wrapper);
return Result.success("取消认证成功");
}
/**
* 用户点击同意后 或 超时后,浏览器发送请求删除该项数据
*
* @param params
*/
@PostMapping("delete/scene")
public void delete(@RequestBody JSONObject params){
String scene = params.getString("scene");
loginService.delete(scene);
}
/**
* 浏览器查询 当前二维码状态
*
* @param scene 场景值
* @return 登录状态
*/
@GetMapping("login/status")
public Login getLoginStatus(@RequestParam(value = "scene") String scene){
QueryWrapper<Login> wrapper = new QueryWrapper<>();
wrapper.eq("scene",scene);
return loginService.getOne(wrapper);
}
@PostMapping("user/detail")
public Result<?> getUserDetail(@RequestBody JSONObject params){
QueryWrapper<User> wrapper = new QueryWrapper<>();
wrapper.eq("id", params.getString("userid"));
User user = userService.getOne(wrapper);
return Result.success(user);
}
/**
* 添加用户
*
* @param user 用户信息
*/
private void getUserInfo(User user){
QueryWrapper<User> wrapper = new QueryWrapper<>();
wrapper.eq("openid",user.getOpenid());
User user1 = userService.getOne(wrapper);
// 如果数据库已存在这个用户,则更新用户信息
if(user1 == null){
userService.save(user);
}else {
user.setId(user1.getId());
}
userService.update(user,wrapper);
}
}
LoginMapper
package com.bn.ies.appapi.scanLogin.dao;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.bn.ies.appapi.scanLogin.pojo.dto.Login;
import org.apache.ibatis.annotations.Mapper;
import org.springframework.stereotype.Repository;
/**
* @author 蓝之静云
*/
@Mapper
@Repository
public interface LoginMapper extends BaseMapper<Login> {
}
UserMapper
package com.bn.ies.appapi.scanLogin.dao;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.bn.ies.appapi.scanLogin.pojo.dto.User;
import org.apache.ibatis.annotations.Mapper;
import org.springframework.stereotype.Repository;
/**
* @author 蓝之静云
*/
@Mapper
@Repository
public interface UserMapper extends BaseMapper<User> {
}
Login
package com.bn.ies.appapi.scanLogin.pojo.dto;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import io.swagger.annotations.ApiModelProperty;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.ToString;
/**
* @author 蓝之静云
*/
@Data
@TableName("scan_login")
public class Login {
@TableId(type = IdType.ID_WORKER_STR)
@TableField(value = "id")
@ApiModelProperty(value = "主键ID")
private String id;
/**
* 场景随机值
*/
@TableField(value = "scene")
@ApiModelProperty(value = "场景随机值")
String scene;
/**
* 扫码状态
*/
@TableField(value = "status")
@ApiModelProperty(value = "扫码状态")
String status;
/**
* 用户id
*/
@TableField(value = "userid")
@ApiModelProperty(value = "用户id")
String userid;
/**
* code码
*/
@TableField(exist = false)
String code;
/**
* 用户头像
*/
@TableField(value = "avatar")
@ApiModelProperty(value = "用户头像")
String avatar;
}
User
package com.bn.ies.appapi.scanLogin.pojo.dto;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import io.swagger.annotations.ApiModelProperty;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
/**
* @author 蓝之静云
*/
@Data
@TableName("scan_user")
public class User {
@TableId(type = IdType.ID_WORKER_STR)
@TableField(value = "id")
@ApiModelProperty(value = "主键ID")
private String id;
/**
* 用户名
*/
@TableField(value = "nickname")
@ApiModelProperty(value = "用户名")
String nickname;
/**
* 用户唯一标识
*/
@TableField(value = "openid")
@ApiModelProperty(value = "用户唯一标识")
String openid;
/**
* 用户头像
*/
@TableField(value = "avatar")
@ApiModelProperty(value = "用户头像")
String avatar;
/**
* code码
*/
@TableField(exist = false)
String code;
}
LoginServiceImpl
package com.bn.ies.appapi.scanLogin.service.impl;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.bn.df.common.api.vo.Result;
import com.bn.ies.appapi.scanLogin.dao.LoginMapper;
import com.bn.ies.appapi.scanLogin.pojo.dto.Login;
import com.bn.ies.appapi.scanLogin.service.LoginService;
import com.bn.ies.appapi.scanLogin.utils.FileManage;
import com.bn.ies.base.config.FileProperties;
import com.bn.ies.base.entity.po.SysUser;
import com.bn.ies.util.HeaderUtil;
import com.bn.ies.util.IscPropertiesUtils;
import com.bn.ies.util.UserUtil;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicHeader;
import org.apache.http.protocol.HTTP;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;
import javax.servlet.http.HttpServletRequest;
import java.io.*;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
/**
* @author 蓝之静云
*/
@Service
public class LoginServiceImpl extends ServiceImpl<LoginMapper, Login> implements LoginService {
@Value("${wxmini.appid}")
private String appid;
@Value("${wxmini.secret}")
private String secret;
@Autowired
private FileProperties properties;
@Autowired
private RestTemplate restTemplate;
@Override
public String createAndGetQrcodeFile(String s) {
// 1、创建文件名及scene值
String scene = UUID.randomUUID().toString().replaceAll("-", "");
// 2、获取token
String accessToken = getAccessToken();
System.out.println("accessToken = " + accessToken);
// 3、请求图片流
InputStream inputStream = getwxacode(accessToken, scene);
System.out.println("input"+inputStream);
// 删除原有图标文件(若存在)
FileManage.delFileByPath(properties.getPath().getQrCode() + File.separator + s + ".jpg");
// 4、保存图标文件
saveToImgByInputStream(inputStream,scene);
// 5、删除冗余数据
this.delete(s);
// 6、数据库增加该项数据
Login login = new Login();
login.setScene(scene);
this.save(login);
return scene;
}
@Override
public SysUser getUserInfoByOpenid(String openid, HttpServletRequest request) {
SysUser sysUser = new SysUser();
try {
//设置请求头携带token
HttpHeaders headers = HeaderUtil.getHttpHeaders(UserUtil.getToken(request));
JSONObject json = new JSONObject();
json.put("openid", openid);
org.springframework.http.HttpEntity<JSONObject> params = new org.springframework.http.HttpEntity<>(json, headers);
//请求获取用户列表
ResponseEntity<Result> usernameListResponse = restTemplate.exchange(IscPropertiesUtils.getUserInfoByOpenidUrl(), HttpMethod.POST, params, Result.class);
Map userInfo = (HashMap)usernameListResponse.getBody().getResult();
sysUser.setAvatar((String)userInfo.getOrDefault("avatar", ""));
sysUser.setUsername((String)userInfo.getOrDefault("username", ""));
} catch (Exception e) {
return sysUser;
}
return sysUser;
}
@Override
public void delete(String scene) {
// 删除数据库信息
QueryWrapper<Login> wrapper = new QueryWrapper<>();
wrapper.eq("scene", scene);
this.remove(wrapper);
// 删除图片文件
FileManage.delFileByPath(properties.getPath().getQrCode() + File.separator + scene + ".jpg");
}
/**
* 获取access_token
* @return access_token
*/
private String getAccessToken(){
RestTemplate restTemplate = new RestTemplate();
Map<String, String> params = new HashMap<>();
params.put("APPID", appid);
params.put("APPSECRET", secret);
ResponseEntity<String> responseEntity = restTemplate.getForEntity(
"https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={APPID}&secret={APPSECRET}",
String.class, params);
String body = responseEntity.getBody();
JSONObject object = JSON.parseObject(body);
return object.getString("access_token");
}
/**
1. 带参数有限个数小程序码接口
2. @param url
3. @param access_token
4. @param path
5. @param width
6. @return
*/
private static InputStream getwxacode(String accessToken, String scene){
String url = "https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token=" + accessToken;
JSONObject jsonParam = new JSONObject();
// 封装请求对象
// scene值
jsonParam.put("scene", scene);
// 跳往的小程序页面,一般为认证界面
jsonParam.put("page","pages/oauth/oauth");
// 图片宽度,默认为 430
jsonParam.put("width","430");
// 检测页面是否存在,默认为 true
jsonParam.put("check_path",true);
// 返回请求结果
return doWxPost(url, jsonParam);
}
/**
* IO流保存图片
*
* @param instreams 需要保存的流
* @param imagePath 保存的图片路径
* @param fileName 文件名
* @return 保存状态
*/
private static boolean uploadImages( InputStream instreams,String imagePath,String fileName) {
File f = new File(imagePath);
f.setWritable(true, false);
boolean flag = false;
try {
// 1K的数据缓冲
byte[] bs = new byte[1024];
// 读取到的数据长度
int len;
// 输出的文件流
File file = new File(imagePath,fileName);
if (!file.getParentFile().exists()) {
file.getParentFile().mkdirs();
try {
// 创建新文件
file.createNewFile();
} catch (IOException e) {
System.out.println("创建新文件时出现了错误。。。");
e.printStackTrace();
}
}
OutputStream os = new FileOutputStream(imagePath+File.separator+fileName);
// 开始读取
while ((len = instreams.read(bs)) != -1) {
os.write(bs, 0, len);
}
// 完毕,关闭所有链接
os.close();
instreams.close();
flag = true;
} catch (IOException e) {
e.printStackTrace();
}
return flag;
}
/**
* 通过流保存图片
*
* @param instreams 二进制流
* @param fileName 图片的名称
*/
private void saveToImgByInputStream(InputStream instreams, String fileName) {
if (instreams != null) {
boolean b = uploadImages(instreams, properties.getPath().getQrCode(), fileName + ".jpg");
}
}
/**
* 发送post请求
*
* @param url 请求地址
* @param jsonParam 请求参数
* @return 响应流
*/
private static InputStream doWxPost(String url, JSONObject jsonParam) {
InputStream instreams = null;
// 创建HttpPost对象
HttpPost httpRequst = new HttpPost(url);
try {
StringEntity se = new StringEntity(jsonParam.toString(),"utf-8");
se.setContentType("application/json");
se.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE,"UTF-8"));
httpRequst.setEntity(se);
HttpResponse httpResponse = new DefaultHttpClient().execute(httpRequst);
if (httpResponse.getStatusLine().getStatusCode() == 200) {
HttpEntity httpEntity = httpResponse.getEntity();
if (httpEntity != null) {
instreams = httpEntity.getContent();
}
}
} catch (IOException e) {
e.printStackTrace();
}
return instreams;
}
}
UserServiceImpl
package com.bn.ies.appapi.scanLogin.service.impl;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.bn.ies.appapi.scanLogin.dao.UserMapper;
import com.bn.ies.appapi.scanLogin.pojo.dto.User;
import com.bn.ies.appapi.scanLogin.service.UserService;
import org.springframework.stereotype.Service;
/**
* @author 蓝之静云
*/
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {
}
LoginService
package com.bn.ies.appapi.scanLogin.service;
import com.baomidou.mybatisplus.extension.service.IService;
import com.bn.ies.appapi.scanLogin.pojo.dto.Login;
import com.bn.ies.base.entity.po.SysUser;
import javax.servlet.http.HttpServletRequest;
/**
* @author 蓝之静云
*/
public interface LoginService extends IService<Login> {
/**
* 请求创建图片文件并返回文件名
*
* @return 返回scene值,作为网站做剩余操作的依据
*/
String createAndGetQrcodeFile(String scene);
/**
* 通过openid获取用户信息
* @return
*/
SysUser getUserInfoByOpenid(String openid, HttpServletRequest request);
/**
* 根据场景值执行删除冗余数据
* @param scene
*/
void delete(String scene);
}
UserService
package com.bn.ies.appapi.scanLogin.service;
import com.baomidou.mybatisplus.extension.service.IService;
import com.bn.ies.appapi.scanLogin.pojo.dto.User;
/**
* @author 蓝之静云
*/
public interface UserService extends IService<User> {
}
FileManage
package com.bn.ies.appapi.scanLogin.utils;
import org.springframework.web.multipart.MultipartFile;
import java.io.File;
import java.io.IOException;
import java.util.UUID;
/**
* 文件管理工具
*
* @author 蓝之静云
*/
public class FileManage {
/**
* 根据路径和文件名删除图片
*
* @param path 路径和文件名
* @return 1表示删除成功
* 0表示删除失败
* -1表示文件不存在
*/
public static int delFileByPath(String path){
int resultInfo;
File file = new File(path);
//文件是否存在
if (file.exists()) {
//存在就删了,返回1
if (file.delete()) {
resultInfo = 1;
} else {
resultInfo = 0;
}
} else {
resultInfo = -1;
}
return resultInfo;
}
/**
* 上传保存图片
*
* @param file 文件
* @param uploadPath 上传路径
* @return 文件名
* @throws IOException
*/
public static String saveUploadFile(MultipartFile file, String uploadPath) throws IOException {
// 获取文件名
String fileName = file.getOriginalFilename();
String subfix = fileName.substring(fileName.lastIndexOf("."));
String uploadFileName = UUID.randomUUID().toString() + subfix;
System.out.println("上传文件名 : " + uploadFileName);
//如果路径不存在,创建一个
File realPath = new File(uploadPath);
if (!realPath.exists()) {
realPath.mkdir();
}
System.out.println("上传文件保存地址:"+realPath);
file.transferTo(new File(uploadPath+"/"+uploadFileName));
return uploadFileName;
}
}
FileProperties
/*
* Copyright 2019-2020 WuTongyue
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.bn.ies.base.config;
import com.bn.ies.base.constant.PhysicsConstant;
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;
/**
* @author WuTongyue
* @date 2023/03/17
*/
@Data
@Configuration
@ConfigurationProperties(prefix = "file")
public class FileProperties {
/** 文件大小限制 */
private Long maxSize;
private ElPath mac;
private ElPath linux;
private ElPath windows;
public ElPath getPath(){
String os = System.getProperty("os.name");
if(os.toLowerCase().startsWith(PhysicsConstant.WIN)) {
return windows;
} else if(os.toLowerCase().startsWith(PhysicsConstant.MAC)){
return mac;
}
return linux;
}
@Data
public static class ElPath{
private String qrCode;
}
}