com.hn.upload.LocalUpload Maven / Gradle / Ivy
package com.hn.upload;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.StrUtil;
import com.hn.config.HnConfigUtils;
import com.hn.config.exception.ConfigException;
import com.hn.utils.AssertUtils;
import lombok.Data;
import java.io.File;
import java.io.InputStream;
/**
* 描述:
* 本地上传
*
* @author fei
* 2021-01-12 07:00
*/
public class LocalUpload extends AbstractFileUpload {
/**
* 参数
*/
private final Param param;
public static Param createParam() {
return new Param();
}
public LocalUpload(Param param) {
checkParam(param);
this.param = param;
}
public LocalUpload(String scene) {
Param param = getRequestParam(scene);
checkParam(param);
this.param = param;
}
@Override
public String getFileBaseUrl() {
return param.fileUrl;
}
@Override
public String getTempDownUrl(String key, Integer expireTime) {
throw new UploadException("本地上传不支持临时下载地址");
}
/**
* 文件上传
*
* @param file 上传的文件
* @param objectName 上传文件到本地时需要指定包含文件后缀在内的完整路径,例如abc/efg/123.jpg。
* @return objectName
*/
@Override
public String uploadFile(File file, String objectName) {
FileUtil.copy(file,new File(param.getSavePath()+objectName),true);
return objectName;
}
/**
* 文件上传
*
* @param is 上传的文件流
* @param objectName 上传文件到OSS时需要指定包含文件后缀在内的完整路径,例如abc/efg/123.jpg。
* @return objectName
*/
@Override
public String uploadFile(InputStream is, String objectName) {
FileUtil.writeFromStream(is,new File(param.getSavePath()+objectName));
return objectName;
}
@Override
public void deleteFile(String objectName) {
FileUtil.del(new File(param.getSavePath()+objectName));
}
/**
* 直传
* @return map
*/
@Override
public Object getToken() {
throw new UploadException("本地上传不支持getToken");
}
@Override
public Object getToken(String dir) {
throw new UploadException("本地上传不支持getToken");
}
private void checkParam(Param param) {
AssertUtils.notNull(param, "param is null");
AssertUtils.notNull(param.savePath, ConfigException.exception("本地存储 savePath 未配置"));
AssertUtils.notNull(param.fileUrl, ConfigException.exception("本地存储 fileUrl 未配置"));
}
/**
* 配置前缀名
*/
private static final String CONFIG_KEY = "upload.local";
/**
* 获取数据配置
*
* @return Param
*/
private Param getRequestParam(String scene) {
String configKey = CONFIG_KEY;
if (StrUtil.isNotBlank(scene)) {
configKey = configKey.concat("-").concat(scene);
}
String savePath = HnConfigUtils.getConfig(configKey.concat(".savePath"));
String fileUrl = HnConfigUtils.getConfig(configKey.concat(".fileUrl"));
Param param = new Param();
// 从数据库读取配置
param.setSavePath(savePath+"/");
param.setFileUrl(fileUrl);
return param;
}
@Data
public static class Param {
/**
* 【本地存储】存储路径
*/
private String savePath;
/**
* 【本地存储】fileUrl
*/
private String fileUrl;
}
}
© 2015 - 2024 Weber Informatics LLC | Privacy Policy