图片上传/保存/删除文件夹/base64转换
图片上传/保存
@PostMapping("/newStaffSubmit")
public PageResult<Object> addRegister(@RequestParam("fileList") List<MultipartFile> fileList, RegisterQuery registerQuery, HttpServletRequest request) {
return personService.addRegister(fileList, registerQuery, request);
}
@Transactional(rollbackFor = Exception.class)
@Override
public PageResult<Object> addRegister(List<MultipartFile> fileList, RegisterQuery registerQuery, HttpServletRequest request) {
//先判断该用户,是否已存在(通过)/或者正在申请中(未审批)
String phone = registerQuery.getContact();
PageResult<Object> personResult = checkPerson(phone);
if (personResult != null) {
return personResult;
}
//保存图片到服务器,并返回路径
PageResult<Object> result = saveMessages(fileList, request, phone);
if (result != null) {
return result;
}
registerQuery.setTime(DateUtils.getTheCurrentTime("yyyy-MM-dd HH:mm:ss"));
String type = "0";
if (type.equals(registerQuery.getType())) {
//数据存入注册申请表
insertRegisteration(registerQuery, phone, "0");
} else {
//数据存入注册申请表
insertRegisteration(registerQuery, phone, "1");
//并且直接入人员管理表
insertPersonManagement(registerQuery, phone);
}
return ResultUtil.success("注册成功");
}
private PageResult<Object> saveMessages(List<MultipartFile> fileList, HttpServletRequest request, String phone) { Map<String, Object> map = Maps.newHashMap(); List<String> filePath = new ArrayList<>(); // 文件后缀名 String extName = ""; // 文件名字 String firstName = ""; // 指定文件名 可以为空不指定 String fileName = request.getParameter("fileName"); // 组装文件保存路径 // 文件保存路径 String path = "/" + phone + "/"; // 文件输入、输出流 FileOutputStream outputStream = null; InputStream inputStream = null; String originalFilename; for (MultipartFile file : fileList) { try { if (file == null) { log.error("未获取到文件!"); map.put("errno", 1); map.put("messages", "未获取到文件"); log.error(map); return ResultUtil.error("未获取到文件"); } originalFilename = file.getOriginalFilename(); assert originalFilename != null; originalFilename = getFileName(originalFilename); // 名字 if (StringUtils.isBlank(originalFilename)) { log.info("未获取到文件的名字!"); map.put("errno", 1); map.put("messages", "未获取到文件的名字"); return ResultUtil.error("未获取到文件的名字"); } //获取文件后缀类型 if (originalFilename.lastIndexOf(".") > 0) { extName = originalFilename.substring(originalFilename.lastIndexOf(".") + 1); firstName = originalFilename.substring(0, originalFilename.lastIndexOf(".")); } // 远程服务器上传目录 File f1 = new File(uploadBasePath + path); if (!f1.exists()) { boolean mkdirs = f1.mkdirs(); log.info("是否穿件文件夹" + mkdirs); } String fileName1 = UUID.randomUUID().toString().replace("-", ""); // 保存的文件名称 if (StringUtils.isNotBlank(fileName)) { fileName1 = fileName + fileName1 + "." + extName; } else { fileName1 = firstName + fileName1 + "." + extName; } oneMessagePath = uploadBasePath + path + fileName1; log.info(filePath); log.info("--------上传路径[{}]", path + fileName1); filePath.add(path + fileName1); outputStream = new FileOutputStream(uploadBasePath + path + fileName1); inputStream = file.getInputStream(); byte[] buf = new byte[1024]; int length; while ((length = inputStream.read(buf)) != -1) { outputStream.write(buf, 0, length); } } catch (Exception e) { map.put("errno", 1); map.put("messages", "保存文件出错 ,请检查上传文件是否有误!"); log.error("上传文件失败,失败原因:", e); return ResultUtil.error("保存文件出错 ,请检查上传文件是否有误!"); } finally { //关闭流资源 closeIo(outputStream, inputStream); } } return null; }
/**
* 获取文件后缀
*
* @param fileName 文件名
* @return fileName
* @author liubo
*/
public static String getFileName(String fileName) {
//检查unix样式的路径
int unixSep = fileName.lastIndexOf('/');
//检查windows样式的路径
int winSep = fileName.lastIndexOf('\\');
//在最可能的点被切断
int pos = (Math.max(winSep, unixSep));
if (pos != -1) {
//找到的任何路径分隔符。
fileName = fileName.substring(pos + 1);
}
return fileName;
}
/**
* 关闭流
*
* @param outputStream 输出流
* @param inputStream 输入流
*/
private void closeIo(FileOutputStream outputStream, InputStream inputStream) {
try {
if (outputStream != null) {
outputStream.close();
}
} catch (IOException e) {
e.printStackTrace();
}
try {
if (inputStream != null) {
inputStream.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
删除文件夹
/** * 删除指定文件夹下的全部内容 * * @param file 文件 */ public static void removeFile(File file) { //将file子目录及子文件放进文件数组 File[] files = file.listFiles(); //如果包含文件进行删除操作 if (files != null) { for (File value : files) { //删除子文件 if (value.isFile()) { try { Files.delete(value.toPath()); } catch (IOException e) { throw new IllegalArgumentException(e); } } else if (value.isDirectory()) { //通过递归方法删除子目录的文件 remove(value); } } //删除子目录 boolean delete = file.delete(); log.info("删除子目录" + delete); } }
base64转换
package com.hlkj.workpc.util; import sun.misc.BASE64Decoder; import sun.misc.BASE64Encoder; import java.io.*; /** * 图片转换工具类 * * @author hwx * @date 2023/3/20 **/ public class Base64Utils { /** * 图片转base64字符串 * * @param imgFile 图片路径 * @return */ public static String imageToBase64Str(String imgFile) { InputStream inputStream = null; byte[] data = null; try { inputStream = new FileInputStream(imgFile); data = new byte[inputStream.available()]; inputStream.read(data); inputStream.close(); } catch (IOException e) { e.printStackTrace(); } // 加密 BASE64Encoder encoder = new BASE64Encoder(); return encoder.encode(data); } /** * base64编码字符串转换为图片,并写入文件 * * @param imgStr base64编码字符串 * @param path 图片路径 * @return */ public static boolean base64StrToImage(String imgStr, String path) { if (imgStr == null) { return false; } BASE64Decoder decoder = new BASE64Decoder(); try { // 解密 byte[] b = decoder.decodeBuffer(imgStr); // 处理数据 for (int i = 0; i < b.length; ++i) { if (b[i] < 0) { b[i] += 256; } } //文件夹不存在则自动创建 File tempFile = new File(path); if (!tempFile.getParentFile().exists()) { tempFile.getParentFile().mkdirs(); } OutputStream out = new FileOutputStream(tempFile); out.write(b); out.flush(); out.close(); return true; } catch (Exception e) { return false; } } }