springboot监听文件新增文件并上传OSS

news/2024/11/14 14:32:32/

记录工作中的一点失误,ossUtil类中的属性filedir(文件存储目录)需要“/”才能生成目录

项目中的本地文件夹和oss上的文件夹是一样的,是由传入controller的参数决定的

一、项目目录

 

二、加入jar

 三、代码

        1.Config

FileListener
package com.ssm.boot.config;import com.ssm.boot.Utils.OssUtil;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.IOUtils;
import org.apache.commons.io.monitor.FileAlterationListenerAdaptor;
import org.apache.commons.io.monitor.FileAlterationObserver;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mock.web.MockMultipartFile;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;import java.io.*;/*** Created by Rick on 2017/12/18.** 文件变化监听器** 在Apache的Commons-IO中有关于文件的监控功能的代码. 文件监控的原理如下:* 由文件监控类FileAlterationMonitor中的线程不停的扫描文件观察器FileAlterationObserver,* 如果有文件的变化,则根据相关的文件比较器,判断文件时新增,还是删除,还是更改。(默认为1000毫秒执行一次扫描)***/
@Slf4j
@Component
public class FileListener extends FileAlterationListenerAdaptor {@Autowiredprivate OssUtil ossUtil;/*** 文件创建执行*/@SneakyThrows@Overridepublic void onFileCreate(File file) {log.info("[新建txt]:" + file.getAbsolutePath());File file1 = new File(file.getAbsolutePath());log.info("[新建1]:" +file1);String s = file1.getParent().substring(15);FileInputStream input = new FileInputStream(file1);log.info("[新建3]:" +input);MultipartFile multipartFile =new MockMultipartFile("file",file.getName(), "image/jpeg", IOUtils.toByteArray(input));log.info("[新建4]:" + multipartFile);//调用OSS工具类ossUtil.setFiledir(s+"/");ossUtil.checkImage(multipartFile);log.info("上传成功");}/*** 文件创建修改*/@Overridepublic void onFileChange(File file) {log.info("[修改]:" + file.getAbsolutePath());BufferedReader buf = null;try {buf = new BufferedReader(new InputStreamReader(new FileInputStream(file),"GBK"));BufferedReader br = new BufferedReader(buf);String line = null;System.out.println(br.readLine());} catch (IOException e) {e.printStackTrace();} finally {// 这里释放系统 IO 资源try {if (buf != null){buf.close();}}catch (Exception e){}}}/*** 文件删除*/@Overridepublic void onFileDelete(File file) {log.info("[删除]:" + file.getAbsolutePath());}/*** 目录创建*/@Overridepublic void onDirectoryCreate(File directory) {log.info("[新建]:" + directory.getAbsolutePath());}/*** 目录修改*/@Overridepublic void onDirectoryChange(File directory) {log.info("[修改]:" + directory.getAbsolutePath());}/*** 目录删除*/@Overridepublic void onDirectoryDelete(File directory) {log.info("[删除]:" + directory.getAbsolutePath());}@Overridepublic void onStart(FileAlterationObserver observer) {// TODO Auto-generated method stubsuper.onStart(observer);}@Overridepublic void onStop(FileAlterationObserver observer) {// TODO Auto-generated method stubsuper.onStop(observer);}
}
FilterFileConfig
package com.ssm.boot.config;import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.filefilter.FileFilterUtils;
import org.apache.commons.io.filefilter.HiddenFileFilter;
import org.apache.commons.io.filefilter.IOFileFilter;
import org.apache.commons.io.monitor.FileAlterationMonitor;
import org.apache.commons.io.monitor.FileAlterationObserver;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;import java.io.File;
import java.util.concurrent.TimeUnit;@Configuration
@Slf4j
public class FilterFileConfig {@Autowiredprivate FileListener fileListener;public void FileFilter(String rootDir){// 监控目录//String rootDir = "D:\\oss";// 轮询间隔 5 秒long interval = TimeUnit.SECONDS.toMillis(1);// 创建过滤器IOFileFilter directories = FileFilterUtils.and(FileFilterUtils.directoryFileFilter(),HiddenFileFilter.VISIBLE);IOFileFilter files = FileFilterUtils.and(FileFilterUtils.fileFileFilter(),FileFilterUtils.suffixFileFilter(".jpeg"));IOFileFilter filter = FileFilterUtils.or(directories, files);// 使用过滤器FileAlterationObserver observer = new FileAlterationObserver(new File(rootDir), filter);//FileAlterationObserver observer = new FileAlterationObserver(new File(rootDir));observer.addListener(fileListener);//创建文件变化监听器FileAlterationMonitor monitor = new FileAlterationMonitor(interval, observer);// 开始监控try{monitor.start();System.out.println("***************监控中***************");}catch (Exception e){log.error("异常处理",e);}}
}

        2.controller

FilterController
package com.ssm.boot.controller;import com.ssm.boot.Utils.OssUtil;
import com.ssm.boot.config.FilterFileConfig;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;import java.io.File;
import java.io.IOException;@RestController
@Slf4j
public class FilterController {@Autowiredprivate FilterFileConfig filterFileConfig;@GetMapping("/file")public void file(@RequestParam("lastPath")String lastPath, Model model) throws IOException {String rootDir = "C:\\Users\\admin\\"+lastPath;OssUtil ossUtil = new OssUtil();File file = new File(rootDir);if (!file.isDirectory()){file.mkdirs();file.createNewFile();model.addAttribute("msg","文件创建成功");}else {file.createNewFile();model.addAttribute("msg","文件夹已存在!");}filterFileConfig.FileFilter(rootDir);}
}

        3.Utils

OssUtil
package com.ssm.boot.Utils;import com.aliyun.oss.OSSClient;
import com.aliyun.oss.model.ObjectMetadata;
import com.aliyun.oss.model.PutObjectResult;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.Date;
import java.util.List;
import java.util.Random;/*** @Description: 阿里云OSS服务器工具类* @author: Yangxf* @date: 2019/4/18 16:26*/@Component
@Data
@Slf4j
public class OssUtil {@Value("${aliyun.oss.endpoint}")private String endpoint;@Value("${aliyun.oss.accessKeyId}")private String accessKeyId;@Value("${aliyun.oss.accessKeySecret}")private String accessKeySecret;@Value("${aliyun.oss.bucketName}")private String bucketName;//文件存储目录private String filedir;//该属性需要" / "才能生成目录/**** 上传图片* @param file* @return*/public String uploadImg2Oss(MultipartFile file) {if (file.getSize() > 1024 * 1024 *20) {return "图片太大";//RestResultGenerator.createErrorResult(ResponseEnum.PHOTO_TOO_MAX);}String originalFilename = file.getOriginalFilename();String substring = originalFilename.substring(originalFilename.lastIndexOf(".")).toLowerCase();Random random = new Random();String name = random.nextInt(10000) + System.currentTimeMillis() + substring;try {InputStream inputStream = file.getInputStream();this.uploadFile2OSS(inputStream, name);return name;//RestResultGenerator.createSuccessResult(name);} catch (Exception e) {return "上传失败";//RestResultGenerator.createErrorResult(ResponseEnum.PHOTO_UPLOAD);}}/*** 上传图片获取fileUrl* @param instream* @param fileName* @return*/private String uploadFile2OSS(InputStream instream, String fileName) {String ret = "";try {//创建上传Object的MetadataObjectMetadata objectMetadata = new ObjectMetadata();objectMetadata.setContentLength(instream.available());objectMetadata.setCacheControl("no-cache");objectMetadata.setHeader("Pragma", "no-cache");objectMetadata.setContentType(getcontentType(fileName.substring(fileName.lastIndexOf("."))));objectMetadata.setContentDisposition("inline;filename=" + fileName);//上传文件OSSClient ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret);PutObjectResult putResult = ossClient.putObject(bucketName, filedir + fileName, instream, objectMetadata);ret = putResult.getETag();} catch (IOException e) {log.error(e.getMessage(), e);} finally {try {if (instream != null) {instream.close();}} catch (IOException e) {e.printStackTrace();}}return ret;}public static String getcontentType(String FilenameExtension) {if (FilenameExtension.equalsIgnoreCase(".bmp")) {return "image/bmp";}if (FilenameExtension.equalsIgnoreCase(".gif")) {return "image/gif";}if (FilenameExtension.equalsIgnoreCase(".jpeg") ||FilenameExtension.equalsIgnoreCase(".jpg") ||FilenameExtension.equalsIgnoreCase(".png")) {return "image/jpeg";}if (FilenameExtension.equalsIgnoreCase(".html")) {return "text/html";}if (FilenameExtension.equalsIgnoreCase(".txt")) {return "text/plain";}if (FilenameExtension.equalsIgnoreCase(".vsd")) {return "application/vnd.visio";}if (FilenameExtension.equalsIgnoreCase(".pptx") ||FilenameExtension.equalsIgnoreCase(".ppt")) {return "application/vnd.ms-powerpoint";}if (FilenameExtension.equalsIgnoreCase(".docx") ||FilenameExtension.equalsIgnoreCase(".doc")) {return "application/msword";}if (FilenameExtension.equalsIgnoreCase(".xml")) {return "text/xml";}return "image/jpeg";}/*** 获取图片路径* @param fileUrl* @return*/public String getImgUrl(String fileUrl) {if (!StringUtils.isEmpty(fileUrl)) {String[] split = fileUrl.split("/");String url =  this.getUrl(this.filedir + split[split.length - 1]);return url;}return null;}/*** 获得url链接** @param key* @return*/public String getUrl(String key) {// 设置URL过期时间为10年  3600l* 1000*24*365*10Date expiration = new Date(System.currentTimeMillis() + 3600L * 1000 * 24 * 365 * 10);// 生成URLOSSClient ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret);URL url = ossClient.generatePresignedUrl(bucketName, key, expiration);if (url != null) {return url.toString();}return null;}/*** 多图片上传* @param fileList* @return*/public String checkList(List<MultipartFile> fileList) {String  fileUrl = "";String  str = "";String  photoUrl = "";for(int i = 0;i< fileList.size();i++){fileUrl = uploadImg2Oss(fileList.get(i));str = getImgUrl(fileUrl);if(i == 0){photoUrl = str;}else {photoUrl += "," + str;}}return photoUrl.trim();}/*** 单个图片上传* @param file* @return*/public String checkImage(MultipartFile file){String fileUrl = uploadImg2Oss(file);String str = getImgUrl(fileUrl);return str.trim();}
}

        4.resources

application.yml

aliyun:oss:endpoint: accessKeyId: accessKeySecret: bucketName: server:port: 9090


http://www.ppmy.cn/news/529876.html

相关文章

晶体管静态参数测试仪系统 能测 IGBT. Mosfet. Diode. BJT......

DCT1401 晶体管静态参数测试仪系统 DCT1401晶体管静态参数测试仪系统能测试很多电子元器件的静态直流参数&#xff08;如击穿电压V(BR)CES/V(BR)DSs、漏电流ICEs/lGEs/IGSs/lDSs、阈值电压/VGE(th)、开启电压/VCE(on)、跨导/Gfe/Gfs、压降/Vf、导通内阻Rds(on)&#xff09;。…

元器件参数测试仪 能测 IGBT. Mosfet. Diode. BJT......

DCT1401 元器件参数测试仪 DCT1401元器件参数测试仪能测试很多电子元器件的静态直流参数&#xff08;如击穿电压V(BR)CES/V(BR)DSs、漏电流ICEs/lGEs/IGSs/lDSs、阈值电压/VGE(th)、开启电压/VCE(on)、跨导/Gfe/Gfs、压降/Vf、导通内阻Rds(on)&#xff09;。 测试种类覆盖 7…

GroupDocs.Conversion Crack,强大 .NET 文档转换组件

GroupDocs.Conversion Crack,强大 .NET 文档转换组件 GroupDocs.Conversion for .NET 可帮助您准确转换流行的文档格式&#xff0c;包括&#xff1a;PDF、HTML、电子邮件、Microsoft Word、Excel、PowerPoint、Project、Photoshop、CorelDraw、AutoCAD、图表、光栅图像文件格式…

跟我学企业级flutter项目:如何重新定制cached_network_image的缓存管理与Dio网络请求

前言 flutter中需要展示网络图片时候&#xff0c;不建议使用flutter原本Image.network()&#xff0c;建议最好还是采用cached_network_image这个三方库。那么我今天就按照它来展开说明&#xff0c;我再做企业级项目时如何重新定制cached_network_image。 由于我的项目网络请求…

java后端高级面试题,线程面试题2022

前言 我们从一个问题引入今天的主题。 在日常业务开发中&#xff0c;我们可能经常听到 DBA 对我们说“不要”&#xff08;注意&#xff1a;不是禁止&#xff09;使用 join&#xff0c;那么为什么 DBA 对 join 这么抵触呢&#xff1f;是 join 本身有问题&#xff0c;还是我们使…

ABBYY最新版本OCR文字图像识别软件v16

FineReader PDF使专业人士在数字化工作场所能够最大限度地提高效率。 FineReader PDF最大特色是采用了ABBYY最新推出的基于AI的OCR技术&#xff0c;可以更轻松地在同一工作流程中对各种文档进行数字化、检索、编辑、加密、共享和协作。 现在&#xff0c;信息工作者能将更多时间…

【HTB】Poison(LFI+文件解析漏洞,ssh转发,vnc)

请访问原文链接&#xff1a;sysin.org/blog/junipe…&#xff0c;查看最新版。原创作品&#xff0c;转载请保留出处。 作者&#xff1a;gc(at)sysin.org&#xff0c;主页&#xff1a;www.sysin.org 防火墙 HA 配置系列文章&#xff1a; Cisco Firepower FTD HA 配置文档Fort…

Juniper SSG 550M NSRP配置文档

主防火墙 unset interface e4 ip 将e4的ip地址删除 set interface e4 zone ha 将e4和HA区域绑定一起 SSG550-> set nsrp cluster id 1 设置cluster组号 SSG550(M)-> set nsrp vsd id 0 设置VSD的组号,这条命令可以不用输入&#xff0c;因为Netscreen防火墙的默认的虚拟安…