x-file-storage实现文件上传
问题:
不使用x-file-storage时如果使用某个云首先需要学习他的sdk,这样很麻烦,而x-file-storage集成了各种云的上传,只需要进行配置即可一行代码进行上传,方便简洁。
简介
一行代码将文件存储到本地、FTP、SFTP、WebDAV、阿里云 OSS、华为云 OBS、七牛云 Kodo、腾讯云 COS、百度云 BOS、又拍云 USS、MinIO、 Amazon S3、GoogleCloud Storage、FastDFS、 Azure Blob Storage、Cloudflare R2、金山云 KS3、美团云 MSS、京东云 OSS、天翼云 OOS、移动 云EOS、沃云 OSS、 网易数帆 NOS、Ucloud US3、青云 QingStor、平安云 OBS、首云 OSS、IBM COS、其它兼容 S3 协议的存储平台。查看 所有支持的存储平台
这是x-file-storage的官方简介
官方地址:X File Storage
这里我们以阿里云的oss举例,其他的云都大差不差的。
java集成x-file-storage
创建springboot项目这里就不说了
1、在pom中引入依赖
<!-- 这是x-file依赖 -->
<dependency>
<groupId>org.dromara.x-file-storage</groupId>
<artifactId>x-file-storage-spring</artifactId>
<version>2.2.1</version>
</dependency>
<!--这是oss的依赖,如果需要的是其他的,可以去官网查看依赖 -->
<dependency>
<groupId>com.aliyun.oss</groupId>
<artifactId>aliyun-sdk-oss</artifactId>
<version>3.16.1</version>
</dependency>
2、在application配置文件中添加
#文件上传
dromara:
x-file-storage: #文件存储配置
default-platform: aliyun-oss-1 #默认使用的存储平台
thumbnail-suffix: ".min.jpg" #缩略图后缀,例如【.min.jpg】【.png】
#对应平台的配置写在这里,注意缩进要对齐
aliyun-oss:
- platform: aliyun-oss-1 # 存储平台标识 -- 需要与默认使用的存储平台
enable-storage: true # 启用存储
access-key: *** # 公钥--这里去oss中自己的存证中心复制
secret-key: *** # 密钥--同上
end-point: oss-cn-chengdu.aliyuncs.com # 地域
bucket-name: dkd-chengdu # 存储桶名称
domain: https://abc.oss-cn-shanghai.aliyuncs.com/ # 访问域名,注意“/”结尾,例如:https://abc.oss-cn-shanghai.aliyuncs.com/
base-path: w5z8/ # 基础路径
3、在需要文件上传的实现类中加上
@Autowired
private FileStorageService fileStorageService;//注入实列
4、FileStorageSerice的参数说明
FileInfo fileInfo = fileStorageService.of(file)
.setPath("upload/") //保存到相对路径下,为了方便管理,不需要可以不写--这里建议以时间保存
.setSaveFilename("image.jpg") //设置保存的文件名,不需要可以不写,会随机生成--这里建议不写,这样文件名就不会重复
.setObjectId("0") //关联对象id,为了方便管理,不需要可以不写
.setObjectType("0") //关联对象类型,为了方便管理,不需要可以不写
.putAttr("role","admin") //保存一些属性,可以在切面、保存上传记录、自定义存储平台等地方获取使用,不需要可以不写
.upload(); //将文件上传到对应地方
5、在启动类加上开启fileStorage注解
@EnableFileStorage
代码实现
//我这里写的很简易-自己的小demo
@RestController
@RequestMapping("/v1/file")
public class fileController {
@Autowired
private FileStorageService fileStorageService;//注入实列
/**
* 通用上传请求(单个)
*/
@PostMapping("/upload")
public String uploadFile(MultipartFile file) throws Exception
{
try
{
// // 上传文件路径
// String filePath = RuoYiConfig.getUploadPath();
// // 上传并返回新文件名称
// String fileName = FileUploadUtils.upload(filePath, file);
// String url = serverConfig.getUrl() + fileName;
String format = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd"))+"/";
FileInfo fileInfo = fileStorageService.of(file)
.setPath(format+file) //保存到相对路径下,为了方便管理,不需要可以不写
.upload();
System.err.println("文件上传成功");
return fileInfo.getUrl();
}
catch (Exception e)
{
System.err.println("上传文件执行失败");
return null;
}
}
}
测试
测试用例
这里偷了个懒,这个测试用例是AI写的
public class FileUploadExample {
public static void main(String[] args) {
String url = "http://localhost:18888/v1/file/upload";
String filePath = "C:\\Users\\86183\\Pictures\\Screenshots\\屏幕截图 2024-09-02 224946.png";
try {
// 创建URL对象
URL obj = new URL(url);
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
// 设置请求方法为POST
con.setRequestMethod("POST");
// 设置请求头
con.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + "boundary");
// 允许输入输出
con.setDoOutput(true);
con.setDoInput(true);
// 获取输出流
DataOutputStream wr = new DataOutputStream(con.getOutputStream());
// 构造文件部分
String boundary = "boundary";
String crlf = "\r\n";
String twoHyphens = "--";
// 文件名
String fileName = filePath.substring(filePath.lastIndexOf(File.separator) + 1);
// 写入边界
wr.writeBytes(twoHyphens + boundary + crlf);
// 写入内容描述
wr.writeBytes("Content-Disposition: form-data; name=\"file\"; filename=\"" + fileName + "\"" + crlf);
// 写入内容类型
wr.writeBytes("Content-Type: image/png" + crlf); // 根据文件类型设置
wr.writeBytes(crlf);
// 读取文件并写入
FileInputStream fis = new FileInputStream(filePath);
byte[] buffer = new byte[4096];
int bytesRead;
while ((bytesRead = fis.read(buffer)) != -1) {
wr.write(buffer, 0, bytesRead);
}
wr.writeBytes(crlf);
// 结束边界
wr.writeBytes(twoHyphens + boundary + twoHyphens + crlf);
// 关闭流
wr.flush();
wr.close();
fis.close();
// 获取响应码
int responseCode = con.getResponseCode();
System.out.println("Response Code : " + responseCode);
// 读取响应
BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
// 打印响应
System.out.println("Response: " + response.toString());
} catch (IOException e) {
e.printStackTrace();
}
}
}
结果
去oss上看看有没有