package com.dobbinsoft.fw.support.storage;
|
import com.dobbinsoft.fw.support.properties.FwObjectStorageProperties;
|
import org.springframework.beans.factory.InitializingBean;
|
import org.springframework.beans.factory.annotation.Autowired;
|
import java.io.*;
|
import java.nio.file.Files;
|
import java.nio.file.Path;
|
import java.nio.file.Paths;
|
/**
|
* ClassName: LocalStorageClient
|
* Description: 本地存储实现
|
*
|
* @author: e-weichaozheng
|
* @date: 2021-03-17
|
*/
|
public class LocalStorageClient implements StorageClient, InitializingBean {
|
@Autowired
|
private FwObjectStorageProperties properties;
|
private String storagePath;
|
@Override
|
public void afterPropertiesSet() throws Exception {
|
storagePath = properties.getLocalPath();
|
// 确保存储路径存在
|
File storageDir = new File(storagePath);
|
if (!storageDir.exists()) {
|
boolean isCreated = storageDir.mkdirs();
|
if (!isCreated) {
|
throw new IOException("Failed to create storage directory: " + storagePath);
|
}
|
}
|
}
|
@Override
|
public StorageResult save(StorageRequest request) {
|
StorageResult result = new StorageResult();
|
String fullPath = buildPath(storagePath, request.getPath(), request.getFilename());
|
String imagePath = buildPath("", request.getPath(), request.getFilename());
|
File file = new File(fullPath);
|
File parentDir = file.getParentFile();
|
if (!parentDir.exists()) {
|
boolean isParentCreated = parentDir.mkdirs();
|
if (!isParentCreated) {
|
result.setSuc(false);
|
return result;
|
}
|
}
|
try (InputStream is = request.getIs(); OutputStream os = new FileOutputStream(file)) {
|
byte[] buffer = new byte[1024];
|
int bytesRead;
|
while ((bytesRead = is.read(buffer)) != -1) {
|
os.write(buffer, 0, bytesRead);
|
}
|
result.setSuc(true);
|
result.setUrl(imagePath);
|
} catch (IOException e) {
|
result.setSuc(false);
|
e.printStackTrace();
|
}
|
return result;
|
}
|
@Override
|
public StoragePrivateResult savePrivate(StorageRequest request) {
|
throw new RuntimeException("不支持私有保存");
|
}
|
@Override
|
public boolean delete(String url) {
|
File file = new File(url);
|
return file.delete();
|
}
|
@Override
|
public boolean deletePrivate(String key) {
|
throw new RuntimeException("不支持私有保存");
|
}
|
@Override
|
public String getPrivateUrl(String key, Integer expireSec) {
|
throw new RuntimeException("不支持私有保存");
|
}
|
@Override
|
public String getKeyFormUrl(String url) {
|
throw new RuntimeException("不支持私有保存");
|
}
|
private String buildPath(String base, String path, String filename) {
|
StringBuilder sb = new StringBuilder(base);
|
if (!base.endsWith(File.separator)) {
|
sb.append(File.separator);
|
}
|
if (path != null && !path.isEmpty()) {
|
sb.append(path);
|
if (!path.endsWith(File.separator)) {
|
sb.append(File.separator);
|
}
|
}
|
sb.append(filename);
|
return sb.toString();
|
}
|
}
|