记录工作中的一点失误,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